python basics

Basic knowledge :

+ : For splicing, the content types on both sides must be the same. If they are inconsistent, they need to be converted according to the conversion, and the faces should be the same, otherwise an error will be reported.

Print("") : The string that needs to be printed is inside the quotation marks. If it is not a string, no quotation marks are required. \n in quotation marks is a newline and does not print.

Triple quotation marks: If a long string needs to be wrapped, it can be enclosed in triple quotation marks ''' '''.

Backslash: If the short string is displayed on two lines, it is \ escaped. If there is \ in the thing to be printed , ① you can use / to escape, ② you can use the original string, that is, use r 'string', print(r ' Let ' s go! ' ) . print(r'C:\prontg'+'\\') This is printing followed by \\ .

Sequence operation :

The most basic data structure is a sequence. Each element in the sequence has a number, that is, its position or index. The index starts from 0. The two most common sequences are lists and tuples.

How-to for all sequences:

Indexing, slicing, adding, multiplying, membership checking, length, min and max.

But because tuples and strings are immutable, neither element assignment nor slice assignment is illegal.

index:

Indices start at 0 . The Str[index]   index uses square brackets.

slice:

[ : : ]    Start bit : Stop bit : Step size The stop bit is not included, it is an open interval

Slices also use square brackets.

Add up:

""+"": that is, concatenate two strings into one string

+ : The types on both sides of the plus sign must be the same

multiplication:

sequence *5 : This sequence will be repeated 5 times to create a new sequence

str = "23"
print(str*5)      2323232323

list = [23]     An empty list is displayed like a = [] .
print(list*5) [23,23,23,23,23]

Membership check: use in

User passwords and passwords that are often used to log in;

length, max, min

Len () max () min ()

max("ingibabgiankgbakg""oingongi") o , is to compare all single characters

v = max([5,6,7],[7,"a",789])
print(v) [7,"a",789]   The comparison between lists only compares the previous number,

The parameters following Max and min must be the same, and comparison between lists and strings is not supported. If two lists are connected, only the value at index 0 of each list is compared, so the element at index 0 should be the same when comparing lists.

example:

Max([5,6,7],["a","b"]) is also an execution error. The front is int and the back is a string. If " 5 " is replaced by 5 , it is [ "a"," b”] .

List :

A list is a series of elements arranged in a specific order. Anything can be added to the list, and there is no relationship between the elements.

Use  []    to denote a list and separate the elements with commas.

If you use the index to get the elements in the list that do not contain [] , it is neat and clean.

list = ["1"]*2

['1', '1']

Empty list and its added elements:

S = [] an empty list

S.append(5)     Add elements to an empty list

Add an element of 5 to it. The print is [5]

List(str) is to fold all the characters inside to form a list ( conversion between strings and lists)

example:

List(“str”) = [“s”,”t”,”r”]

slice assignment

Slices allow you to modify elements in a list, and assigning values ​​to slices makes this even more powerful.

例如:name = [1,2,3,"a","b","c"]   
  name[4:] = 4,5

  name= [1, 2, 3, 'a', 4, 5]

Slices can be replaced with sequences of different lengths

Use the empty slice   name[1:1 to be an empty slice, and put things at index 1 .

name[1:1]=[7,8,9]

name=[1, 7, 8, 9, 2, 3, 'a', 4, 5]  

You can also use empty slices to remove elements

name[4:]=[]

name=[1,7,8,9]

 

A few functions from the list:

remove(value)    removes an element from the list

reverse() reverses the sorting order in the list, which is also permanently modified and has no return value

sort()   This is used to sort the list, permanently modify the list, no return value

If they all start with a letter, they are sorted alphabetically.

sorted()   This is a temporary sorting, with a return value, the original list order remains unchanged

You can use range() to generate a list directly with list(range())

Tuple :

Lists are suitable for storing data sets that may change during the run of the program, lists can be modified, and are essential for dealing with user lists for websites or character lists in games.

A tuple is a series of unmodifiable elements, all saying that a tuple is an immutable list, and unmodifiable refers to the elements in the tuple.

Use parentheses to identify, and elements are also separated by ",".

tuple variable assignment to modify tuple

E.g:

A = (1,2,3,)

A = (4,5,6,)

Now print a again, it will only be (4,5,6,)

string :

All strings are enclosed in quotation marks, and the quotation marks can be single or double quotation marks.

Strings are also unmodifiable. If they need to be modified, they will be reassigned to a variable (or the original variable), that is, by storing a string modification, a new string will be generated.

The list is modified on the original list, and a new list will not be generated.

format usage

join usage

The sequence of join() brackets must be composed of strings, and the elements of the sequence must be strings.

split() usage

Split the string according to the following elements, the return value is a list

replace()

Replace(value , new value )

translate usage

Several of the more commonly used and important methods.

dictionary:

Dictionaries in Python , like dictionaries in everyday life, are designed to make it easy for you to find a specific word (key) to know its definition (value).

Here are some uses of dictionaries:

v represents the state of the board, where each key is a tuple of coordinates;

v Store file modification time, where the key is the file name;

vDigital    Phone / Address Book

Composition of the dictionary

A dictionary consists of keys and their corresponding values. Such key - value pairs are called items. Each key and its value are separated by a colon (:), and items are separated by commas. The entire dictionary is enclosed in curly braces. An empty dictionary It is represented by two curly braces, similar to the following {}

The key must be unique, ( numbers, tuples, strings, booleans can be used as keys, lists and dictionaries cannot be used as keys; --- Because lists and dictionaries (dictionaries are unordered) are mutable, So it cannot be used as a key) and the value in the dictionary can be any value.

Iterate over the list:

Iterate over the keys of the list:

For i in dict.key()

  Print(i)   iterates over the values ​​of the dictionary;

 

cycle:

For loop

For i in item:   is to get the first value in item and store it in variable i .

Item is a factor that stops the loop

Because there are other values ​​in the list, it returns to the first line of the loop.

 After the For loop, the unindented code is executed only once and will not be executed repeatedly. If it needs to be executed repeatedly, it needs to be fully indented.

use:

For loops processing data is a good way to perform an overall operation on a dataset, you can use for to initialize the game - iterate through the list of characters, then add an unindented block of code after the loop to draw all characters on the screen Show a play now button

 

For loop use Note that it starts looping from the index 0 of the list . For is basically not used together with pop, and pop deletion is to delete from the last one.

While loop:

initial value

While condition:

  execute statement

  Change the loop conditional statement

1 prompt = " \ntell me something,and i will repeat it back to you: " 
2 prompt += " \nenter 'quit' to end the program " 
3 massage = "" 
4  while massage != " quit " :
 5      massage = input(prompt) #If       you enter "quit" in this entry, "quit" will still be printed, because at this time you have entered the while loop, 
6          print (massage) #If           you want to enter quit to end, you need to be inside the while loop Add an if to judge. 
7  print ( " game over " )

Just like this:

1 prompt = "\ntell me something,and i will repeat it back to you:"
2 prompt += "\nenter 'quit' to end the program"
3 massage =""
4 while massage != "quit":
5     massage = input(prompt)      
6       if massage != "quit":       #这里加等号可能会更好理解一些
7         print(massage)
8 print("game over")
1   if massage == " quit " :
 2          print ( " game over " )     #You can replace all the statements after the above if with this, the same effect!

Once it enters the condition, it will always execute the statement in the while . If the condition is not changed, it will not exit.

The while uses the state change to change the loop:





               
     else:
11         print(massage)

Using this method to write a loop, this kind of statement requires the position of the semantic input to be in the while , and the print is generally placed in the position of the else .

This means that it is not continue or break, the program is still running down, and has not been terminated.

A for loop is an efficient way to traverse a list, but the list cannot be modified in a for loop, otherwise there is no way to keep track of its elements;

If you want to modify a list while iterating over it, you can use a while loop. By combining while loops with lists and dictionaries, large amounts of input can be collected, stored, and organized for later viewing and display.

   I am still a novice at the moment. If there are any mistakes in the above, you can leave a message and I will modify it! Maybe some of the words in it are wrong, but with the current knowledge, writing these is also easy to remember, pay more attention when writing!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325076171&siteId=291194637