python from basics to UnitTest framework-python basic syntax

1.python environment configuration

python interpreter: convert written code into binary;

pycharm: It is one of Python's IDEs (Integrated Development Environment), used to write code and run/debug code;

vscode, IDEA, notepad...

2. Grammar usage

(1)Print print:print()

(2)Input number:input()

(3)Comments:Single line (#; select multiple lines, press the shortcut key: ctrl + /), multiple lines (3 pairs Double quotes or 3 pairs of single quotes)

(4)cmd terminal runs python code:The name of the python code file

(5)Variable:Variable name = data value (naming convention: must consist of letters, numbers and underscores, and cannot start with a number , no keywords are used)

(6)Data type:Number type: integer type (int), floating point type (float), Boolean type (bool) ;Non-numeric types: string (str), list (list), tuple (tuple), dictionary (dict);type (variable): the type of the variable can be obtained

(7)Formatted output:%d: integer type; %f: floating point type; %s: string (can any type)

# The default display of decimals is 6 digits. If you want to specify how many decimal places to display, %.nf and n need to be replaced with specific integer numbers, that is, the decimal positions are retained.
# %0nd n needs to be replaced by a specific integer number, indicating how many integers there are in total.
# The passing rate of a certain exam is 90%. If you need to display % in formatting, you need to use two %% in writing: print('The passing rate of a certain exam is %d%% ' % num)
# Want to output a newline in the string \n (escape character)
Example: print('My name is %s, age is %d, height is %f m' % (name, age, height))
# print('My name is xx, age is xx, height is xx m, student number xx, the passing rate of this exam is xx%')
print(f'My name is {name}, age is {age}, height is {height} m, student number {stu_num}, the passing rate of this exam is
{num}%')
# string.format()
print('My name is {}, age is {}, height is {} m, student number {}, the passing rate of this exam is {}%'.format(name,age, height,stu_num,num))
print('My name is {}, age is {}, height is {:.3f} m, student number {:06d}, the passing rate of this exam is {}%'.format (name,age,height,stu_num,num))

(8)Arithmetic operator:Priority: Whoever is counted first, then whomever is counted (if you are not sure about the priority, use () ): () > ** > * / // % > + -

(9)Comparison operators:Comparison operators result in bool type

(10)Logical operators:and (and, one false is false); or (or, one true is true); not (not)

(11)if

if judgment condition:
    Write the code that the condition is true (true) and executed
    Write the code that the condition is true (true) and executed
The code written in top format and without indentation has nothing to do with if. It will be executed regardless of whether the condition is true or not.
# 1. if is a keyword, a space is required between it and the subsequent judgment condition
# 2. There needs to be a colon after the judgment condition, no less
# 3. After the colon, press Enter, the code needs to be indented. In pycharm, indentation will be done automatically, usually 4 spaces or a tab key.
# 4. All codes written in the indentation below the if code belong to the code block of the if statement and will be executed when the judgment condition is True.
# 5. Either all the codes in the if code block will be executed, or none of them will be executed.
# 6. After the if code block ends, the code should be written in top format (no more indentation), indicating that it is code unrelated to if

(12)if else

If the condition is true, do something else (the condition is not true), do something else
if judgment condition:
    Write the code that the condition is true (true) and executed
    Write the code that the condition is true (true) and executed
else:
    If the written condition is not true (false), the code will be executed
    If the written condition is not true (false), the code will be executed
# 1. else is a keyword and needs a colon after it
# 2. Enter after the colon, which also needs to be indented.
# 3. The content in the indentation below the else code belongs to the else code block
# 4. If and else code blocks, only one of them will be executed.
# 5. else needs to be used in conjunction with if
# 6. There cannot be other content written in the top box between if else (do not mention elif)

(13)if elif else

if judgment condition 1:
    Judgment condition 1 is established, the code to be executed
elif Judgment condition 2: # Judgment condition 2 will be judged only if judgment condition 1 is not established.
    Code executed when condition 2 is established
else:
    If none of the above conditions are met, the executed code
# 1. elif is also a keyword. There needs to be a space between it and the judgment condition, and a colon is needed after the judgment condition.
# 2. The carriage return after the colon needs to be indented. The code in this indentation represents the elif code block.
# 3. In an if judgment, there can be many elifs
# 4. Only if the condition of if does not hold, the condition of elif will be judged.
# 5. In an if, if there are multiple elifs, as long as one condition is true, all subsequent ones will no longer be judged.
# 6. If elif else structure, the only ones with the same indentation as if are elif and else. If it is other, it means that the judgment structure is over.
if judgment condition 1:
    code executed
if judgment condition 2:
    code executed
if judgment condition 3:
    code executed
# The structure of multiple ifs, each if will be judged, there is no relationship between them

(14)if 嵌套

If nesting means nesting another if within an if(elif else).
Usage scenario: There is a progressive relationship between judgment conditions (the second condition will only be judged if the first condition is met)
if judgment condition 1:
    Judgment condition 1 is established, the code to be executed
    if judgment condition 2:
        Judgment condition 2 is established, the code to be executed
    else:
        Judgment condition 2 is not established, the code to be executed
else:
    Judgment condition 1 is not established, the code to be executed

(15)while circulation

In program development (writing code), there are three major processes (three major structures):
1. Sequence, code from top to bottom, all executed
2. Branches, judgment statements, and selective execution of code
3. Loop, repeatedly execute a certain part of the code
The function of the loop is to make the specified code execute repeatedly
1. Set the initial conditions of the loop (counter)
2. Judgment conditions for writing loops
while judgment condition:
    # 3. Code that needs to be executed repeatedly
    # 4. Change the initial condition of the loop (counter)
#infinite loop
Infinite loop: It is usually a bug caused by the person who writes the code accidentally, and the code keeps running.
Infinite loop: The person who wrote the code deliberately allows the code to execute without limit, and the code keeps running.
Usage scenarios of infinite loop: When writing the loop, it is not sure how many times the loop will be executed.
The use of infinite loops generally adds an if judgment to the loop. When the if condition is established, use the keyword break to terminate the loop.
while True:
    Repeatedly executed code # can be above if
    if judgment condition:
        break # Terminate the loop. When the code execution encounters break, the loop will no longer be executed.
    Repeatedly executed code # can be placed below if

(16)for circulation

The for loop can also cause the specified code to be executed repeatedly (loop)
The for loop can traverse the data in the container (
    Traversal: Take out the data one by one from the container
    Container: It can be simply understood as a box, which can store a lot of data (string str, list list, tuple tuple, dictionary dict)
)
for loop can also be called for traversal
for variable name in container:
    Repeatedly executed code
# 1. for and in are both keywords
# 2. How much data is in the container and how many times will the loop be executed (0 data, executed 0 times, ...)
# 3. Each time it loops, one piece of data in the container will be taken out and saved into the variable in front of the in keyword.

(17)for loops the specified number of times

for variable in range(n):
    Repeatedly executed code
# 1. range() is a function in Python. When used, it can generate integers between [0, n), excluding n. Each one has n numbers, so this loop loops n times.
# 2. Just write n as many times as you want the for loop to loop.
# 3. The value of the variable is also taken out from [0, n) in each cycle. The first time it is obtained is 0, and the last time it is obtained is n-1.
range() deformation
for change in range(a, b):
    Duplicate code
# range(a, b) is used to generate integer numbers between [a, b), excluding b

(18)break 和 continue

break and continue are two keywords in Python that can only be used in loops
break: Terminate the loop, that is, when the code execution encounters break, the loop will no longer be executed and will end immediately.
continue: Skip this loop. That is, when the code execution encounters continue, the remaining code in this loop will no longer be executed and continue with the next loop.

(19)Intercept

Slicing: You can obtain multiple characters in a string (the subscripts of multiple characters are regular, arithmetic sequence)
grammar:
String[start:end:step]
start is the subscript of the starting position, end is the subscript of the ending position (note that the character at this position cannot be obtained) step is the step size, the difference of the arithmetic sequence, the difference between the adjacent character subscripts taken , the default is 1, you don’t need to write it
Example: [1:5:1] # 1 2 3 4
[1:5:2]  # 1 3 
[1:5:3]  # 1 4
[1:5:4]  # 1 

(20)character skewer

#String replacement method replace
String.replace(old_str, new_str, count) # Replace old_str in the string with new_str
- old_str: replaced content
- new_str: the content to be replaced by
- count: the number of replacements, generally not written, the default is to replace all
- Return: the complete string after replacement, note: the original string has not changed
#String split split
String.split(sep, maxsplit) # Split (split) the string according to sep
- sep, how to split the string, the default is whitespace characters (space, newline\n, tab key\t)
- max_split, the number of splits, generally not written, split all
- Return: Split a string into multiple pieces and store them in a list
- Note: If sep is not written, and you want to specify the number of divisions, you need to use it as follows
String.split(maxsplit=n) # n is the number of times
#String link join
String.join(list) #The content in brackets is mainly a list, it can be other containers
# Function: Insert the string between each two adjacent data in the list to form a new string
- The data in the list is separated by commas
- Note: The data in the list must be strings, otherwise an error will be reported

List of (23)

List list is the most commonly used container (data type)
Multiple data can be stored in the list, separated by commas.
Any type of data can be stored in the list
To count the number of occurrences, use the count() method
List.count(data) # Return the number of occurrences of data
#Add data at the end
List.append(data) #Add data to the end of the list
Return: Returned None (keyword, empty). Generally, variables are no longer used to save the returned content.
If you want to view the added list, you need to print the list
#Specify the subscript position to add data
List.insert(subscript, data) #Add data at the specified subscript position. If there is data at the specified subscript position, the original data will be moved backward.
Return: Returned None (keyword, empty). Generally, variables are no longer used to save the returned content.
If you want to view the added list, you need to print the list
#List merge
List 1.extend(List 2) # Add all the data in List 2 to the end of List 1 one by one
Return: Returned None (keyword, empty). Generally, variables are no longer used to save the returned content.
If you want to view the added list, you need to print the list
#Revise
list[subscript] = data
#delete
List.pop(subscript) #Delete the data corresponding to the specified subscript position
1. If the subscript is not written, the last data will be deleted by default (commonly used)
2. Write the existing subscript and delete the data corresponding to the subscript position.
Return: the deleted data returned
List.remove(data value) #Delete based on data value
Return: None
Note: If the data to be deleted does not exist, an error will be reported
List.clear() #Clear data
#Reverse and invert in a list:  
1. List [::-1] # Using the slicing method, you will get a new list, and the original list will not change.
2. List.reverse() # Directly modify the original list and return None
#List copy
Use copy method
variable = list.copy()
#List sorting
List.sort() # Sort in ascending order, from small to large
List.sort(reverse=True) # Sort in descending order, from large to small

(24)Original Group

Tuple: tuple, the characteristics of tuple are very similar to list
the difference:
1. The data content in the tuple cannot be changed, but the data content in the list can be changed.
2. Tuples use (), lists use []

(25)Dictionary

1. Dictionary dict, the data in the dictionary is composed of key (key) value (value) pairs (the key represents the name of the data, and the value is the specific data)
2. In the dictionary, a set of key-value pairs is one piece of data, and multiple key-value pairs are separated by commas.
Variable = {key: value, key:value, ...}
3. The keys in a dictionary are unique and cannot be repeated, and the values ​​can be any data.
4. The keys in the dictionary are generally strings, which can be numbers, not lists.

Guess you like

Origin blog.csdn.net/weixin_61275790/article/details/134491484