[common sense of sorting out basic knowledge of Python]
1, Basic noun interpretation
catalogue
[common sense of sorting out basic knowledge of Python] i. explanation of basic terms
Basic information about Python
2. Basic working mechanism of Python
Bitwise operator (-- operation for binary)
Advantages and disadvantages of recursion
Machine language: instructions that can be processed directly by a computer with a combination of 0 and 1. (the computer cannot directly understand any language other than machine language)
Programming language: used to define the formal language of computer program and the language of communication between human and computer
Interpretive language: compile line by line and execute line by line
Compiled language: unified compilation and one-time execution
Ps: compiled language has fast execution speed; However, it does not have the ability of cross platform execution
High level language
source code
Pseudo code
Interpreter: software used to process code compilation. The compiler runs in an interpretive manner
Compiler: a tool for translating other languages into machine languages. There are two ways of compiler translation - Compilation and interpretation. The difference between the two ways lies in the difference of translation time point
Explanation:
Compilation: the process of translating the code of Python, Java and other programming languages into machine language
flow chart
Character coding table
Mirror source : a place to download software. Python's default image source is foreign, and the access is not stable in the domestic network environment, so the download speed is relatively slow.
Integrated development environment
Program: a collection of instructions. Writing a program is to use instructions to control the computer to do what we want it to do. Programs are used to process data
Executable program
source program
Interactive programming: run the interpreter directly on the terminal without using the file name to execute the program. It can also be called REPL -- read the input, Eval the user input instructions, print the execution results, and finally loop. Python supports interactive programming
source file
Identifier: programmer defined variable name and function name
Reserved word
Keyword: the identifier that Python has used in its own development
Scientific counting method
format
Escape character:
Escape character "\" + the first letter of the function you want to achieve
"\ r" enter (overwrite the previous item); "\ t" horizontal tab (4-digit space); "\ n" line feed; "\ \" is a backslash character; "\ '" single quotation mark; "\ ''" double quotation mark; "\ b" backspace (return to the previous step)
Find out the role of "\ \"
Note: it is used to prompt or explain the function and function of some code to the user. It can appear anywhere in the code. Python The interpreter will ignore comments and do nothing when executing code; Comments can also be used to temporarily remove useless code during debugging programs. The biggest function of annotation is to improve the readability of the program.
Python supports two types of comments: single line comments and multi line comments. Python uses the pound sign # as the symbol of a single line comment. The syntax format is: # comment content; Everything from # beginning to the end of this line is a comment. When the Python interpreter encounters #, it ignores the entire line after it. Multiline annotation refers to annotating the contents of multiple lines (including one line) in a program at one time. Multiline comments are usually used to add copyright or function description letters to Python files, modules, classes or functions. Python multiline comments do not support nesting. Python annotates multiline content with three consecutive single quotation marks' 'or three consecutive double quotation marks''
In addition to adding notes to the code, comments also have another practical function, which is to debug the program. If you guess that there may be a problem with a piece of code, you can annotate the code first, let the Python interpreter ignore the code, and then run it. If the program can be executed normally, it can be said that the error is caused by this code; Conversely, if the same error still occurs, it can be said that the error is not caused by this code. Using comments in the process of debugging programs can narrow the scope of errors and improve the efficiency of debugging programs.
Ps: ① when describing the function of multi line code, the comment is generally placed on the top line of the code; When describing the function of single line code, the comment is generally placed on the right side of the code. ② whether it is multi line comment or single line comment, when the comment characters appear as part of the string, they can no longer be regarded as comment marks, but should be regarded as part of the normal code. ③ Shortcut of comments: select the code range to be commented, press and hold Ctrl + / to comment, and automatically add "#" at the beginning of the selected code line. Uncomment is the same operation.
Summary of the role of quotation marks: three quotation marks are reserved format output? The logical relationship between single quotation marks and double quotation marks: quoting others? Cross use
Program blocking
2, Basic information about Python
1. The origin of Python
Python was founded by Guido van Rossum
Python creation process
Guido's positioning for Python
2. Basic working mechanism of Python
A program written in a compiled language such as C or C + + can be converted from a source file (i.e. C or C + + language) to a language used by your computer (binary code, i.e. 0 and 1). This process is accomplished through the compiler and different tags and options.
When running the program, the connection / transfer software copies your program from the hard disk to memory and runs it. Programs written in Python do not need to be compiled into binary code. You can run the program directly from the source code.
Inside the computer, the Python interpreter converts the source code into an intermediate form called bytecode, and then translates it into the machine language used by the computer and runs it.
3. Python features
advantage:
① Simple and easy to learn
Reading a good Python program feels like reading English, enabling you to focus on solving problems rather than understanding the language itself.
Python has less code than other languages.
Python has extremely simple documentation.
When writing a program in Python, you don't need to consider the underlying details such as how to manage the memory used by your program.
② , free and open source, with good community ecology
Python is one of FLOSS (free / open source software). Users are free to release copies of the software, read its source code, make changes to it, and use part of it in new free software. FLOSS is a concept based on group sharing knowledge.
③ I. explanatory
The function of the program can be explained in the form of comments
④ . portability
Because of its open source nature, python has been ported to many platforms (changed to work on different platforms). These platforms include Linux, Windows, Mac and android platform developed by Google based on Linux. As an interpretive language, Python is naturally cross platform. As long as a corresponding Python interpreter is provided for the platform, python can run on the platform
⑤ . object oriented
Python supports both process oriented and object-oriented programming. In a "process oriented" language, programs are built from processes or simply functions of reusable code. In the "Object-Oriented" language, programs are built by objects composed of data and functions. Functions, modules and strings are objects. In Python, everything is an object
⑥ , scalability
Python's extensibility is reflected in its modules. Python has the most abundant and powerful class libraries in the scripting language. These class libraries cover most application scenarios, such as file I/O, GUI, network programming, database access, text operation and so on. The best embodiment of Python extensibility is that when we need a piece of key code to run faster, we can write it in C or C + + language, and then use them in Python programs.
⑦ . embeddability
Python can be embedded in C/C + + programs to provide script functions to program users.
⑧ , rich library
The python standard library is really huge. It can help handle various tasks, including regular expressions, document generation, unit testing, threads, databases, web browsers, CGI, FTP, e-mail, XML, XML-RPC, HTML, WAV files, cryptosystem, GUI (graphical user interface), Tk and other system related operations. This is called Python's "full-featured" concept. In addition to the standard library, there are many other high-quality libraries, such as wxPython, Twisted, python image library and so on.
⑨ Standard code
Python uses forced indentation to make the code readable. Programs written in Python do not need to be compiled into binary code.
Disadvantages:
① Slow running speed (interpreted languages are slower than compiled languages, but Python's scalability will improve this situation to some extent)
② Lack of Chinese materials and narrow domestic market
4. Application fields of Python
web server application development, cloud infrastructure development, network data collection (crawler), data analysis, quantitative transaction, machine learning, deep learning, automatic testing, automatic operation research, etc
5. How to understand Python as a "glue language"?
glue language is a programming language (usually script language) used to connect software components
Glue language: use input and output commands, interfaces, dynamic link libraries, static link libraries, services, objects, etc.
On the terminal:
You can freely combine Python and other programs as an intermediate processing module. Moreover, some simple scripts only need cat once to understand what it means. An expression is a line of code, the code block has consistent standard indentation, standard naming method, concise language, and supports annotation... If other programs want to access or call, just input the specified data here with a command, and then how to splice; It's OK to deal with it periodically. Output it to a file and wait for other programs to call.
On the system script:
Python has more mathematical and string processing capabilities than SHELL, as well as many easy-to-use iterative methods and many native data structures; Much more code readability than PERL. Compared with ruby and nodejs, almost all the machines are pre installed and have experienced the test of time; Compared with C/C + +, it has one more terminal, and even an enhanced artifact terminal like ipython, which can write the code that is OK into the file while debugging the code. Moreover, the source code can be executed.
data type
1, Classification:
1. The integer type (int / integer) can represent positive numbers, negative numbers and zero
① different hexadecimal representations of integers
Decimal - > the default base number is 0.1.2.3.4.5.6.7.8.9
Binary - > start with 0b , enter 1 every 2 , the basic number is 0.1
Octal - > starting with 0o , every 8 into 1 , the basic number is 0.1.2.3.4.5.6.7
Hexadecimal - > starting with 0x , every 16 into 1 , the basic number is 0.1.2.3.4.5.6.7.8.9 A.B.C.D.E.F
Ps:0b1110110(2)—>0o166(8)—>118(10)—>0x76
Use the rolling phase division method and the more phase subtraction method to calculate the corresponding numbers in different base systems
② conversion code:
Convert other hexadecimal characters to binary, and use the function bin();
Convert other hexadecimal characters to octal, using the function oct()
Convert other hexadecimal characters to hexadecimal, using the function hex()
Convert other hexadecimal characters to decimal, using the function int()
print(bin(10)) # 0b1010 # 1 * 2 ** 3 + 0 * 2 ** 2 + 1 * 2 ** 1 + 0 * 2 ** 0 = 10 print(1 * 2 ** 3 + 0 * 2 ** 2 + 1 * 2 ** 1 + 0 * 2 ** 0) # 10 print(bin(149)) # 0b10010101 # Conversion technique: it can be divided by 2, and the value of the corresponding digit is 0 # It cannot be divided by 2. The value of the corresponding digit is the remainder, and the rest is divided by integer # You can also use the programmer mode of the calculator
③ conversion skills:
Skillfully transform the result by using the relationship between octal, hexadecimal and binary - > replace the equally possible digits with equal possibilities - each digit in octal needs to be represented by three digits in binary, and each digit in hexadecimal needs to be represented by four digits in binary, which is less than the corresponding digit to make up 0
④ the value range of Python integers is unlimited. No matter how large or small numbers are, python can handle them easily. When the value used exceeds the computing power of the computer itself, python will automatically switch to high-precision calculation (large number calculation).
⑤ in order to improve the readability of numbers, python 3 X underline allowed_ As a separator for numbers, including integers and decimals. Usually add an underscore every three numbers, similar to the comma in English numbers. Underscores do not affect the value of the number itself.
[example] click = 1_301_547 distance = 384_000_000
2. Floating point type (float) consists of integer part and decimal part
Ps: ① the storage of floating-point numbers is not accurate, and the number of decimal places may be uncertain when using floating-point numbers for calculation; ② the result of division will become floating-point numbers (with decimal points)
print(1.1+2.2) #3.3000000000000003 print(1.1+2.1) #3.2 from decimal import Decimal #Solve the problem of inaccurate storage of floating point numbers print(Decimal('1.1')+Decimal('2.2')) #3.3 print(8/2) #4.0
3. String type
① Strings are also called immutable character sequences
② Strings can be defined by single quotation marks, double quotation marks and three quotation marks; The string defined by single quotation marks and double quotation marks must be on one line; The string defined by three quotation marks can be distributed on multiple consecutive lines; "+" is used as a connection in the string
str1='The Dragon dives into the abyss and leaps into the sky ' str2="The Dragon dives into the abyss and leaps into the sky" str3="""The Dragon dives into the abyss and leaps into the sky""" str4='''The Dragon dives into the abyss and leaps into the sky''' print(str1+str2) #The Dragon dives into the abyss, the Dragon jumps into the sky, the Dragon dives into the abyss, and the Dragon jumps into the sky
③ String formatting shortcut Alt+Ctrl+L -- code specification
4. Boolean type
① Python has objects for everything. All objects have a Boolean value. You can use the built-in function bool() to obtain the Boolean value of the object
② Boolean values can be used for calculations
[example] print(False + 1) # 1 # print(True + 1) # 2
③ Boolean value is generally used for judgment in development
5. Other data types
complex , list , tuple , dictionary , dictionary
2, Conversion between different types
1. Convert to integer
print(int(100.99)) # 100 converts a floating-point number to an integer, rounding off the decimal part
print(int("100") # 100 converts a string to an integer
print(int(True)) # 1 # Boolean value True converts to integer is # 1
print(int(False)) # 0 # Boolean value False is converted to integer 0
Ps: ① conversion will fail if illegal characters are included
[example] print(int("99.88")) print(int("56ab")) cannot be converted to an integer
② an error will be reported if the basic number is exceeded
[example] the maximum allowed value in octal system is 7, so 29 is not a legal octal number, and {print(int("29",8)) will report an error
③ when using the int() function for type conversion, you can also pass in two parameters, and the second parameter is used to represent the base.
[example] the result of print(int("21",8)) # output is 17 Octal 21, the corresponding decimal number is 17
The result of print(int("F0",16)) # output is 240 F0 in hexadecimal, the corresponding decimal number is 240
2. Convert to floating point number
print(float("12.34") # 12.34 # converts "12.34" of a string to a floating-point number
print(float(23)) # 23.0 # converts an integer to a floating point number
print(float(True)) #1.0 #
print(float(False)) #0.0 #
3. Convert to string
print(str(45)) # '45'
print(str(34.56)) # '34.56'
print(str(True)) # 'True'
4. Convert to Boolean
In Python, only empty string '', '', '', number 0, empty dictionary {}, empty list [], empty tuple (), and empty data None will be converted to False, and others will be converted to True
5. Other type conversion
eval(str) | Used to evaluate a valid Python expression in a string and return an object |
---|---|
chr(x) | Converts an integer to a Unicode character |
ord(x) | Converts a character to its ASCII integer value |
tuple(s) | Convert sequence s to a tuple |
list(s ) | Convert sequence s to a list |
3. Use the function type() to retrieve the type of data
str1=0 str2=0.0 str3='0.0' str4=False print(type(str1),type(str2),type(str3),type(str4),sep=' ') # <class 'int'> <class 'float'> <class 'str'> <class 'bool'>
variable
1. Definition of variables
Data that is reused and often needs to be modified can be defined as variables to improve programming efficiency.
The syntax of defining variables is: name = value, where "=" is used to assign values and "assign variable values to name"
PS: ① variable name: we can understand it as a box. What is in the box is the value on the right. When you need to use variable values, bring the corresponding box. ② A variable is a variable that can be changed and can be modified at any time. ③ Programs are used to process data, and variables are used to store data. ③ If a variable has no type, data has a type; The variable itself can operate
2. Rules for naming variables
Hard rules: ① variable names are composed of letters, numbers and underscores, and numbers cannot begin
② distinguish case
③ try not to use keywords or reserved words
PS: (if the identifier is repeated with the reserved word, the system will give priority to the user-defined identifier)
Non mandatory rules:
① variable names usually use lowercase English letters, and multiple words are connected with underscores.
② protected variables begin with a single underscore.
③ private variables start with two underscores
④ for the sake of understanding, it is better to write code with variable names that are easy to understand. See the meaning of names
PS: variable naming, hump type naming, large hump and small hump;
3. Use of variables
Declare a variable - the value stored in the variable is followed by the equal sign. If we want to use this value, we can find them through variables. The variable name needs to be defined for the first time. When it appears again, the variable can be used to modify the value stored in the variable
a = 45 # variable a holds 45
global variable
local variable
Transformation between local variables and global variables
System variable
environment variable
String format
message = '"The Dragon dives into the abyss and leaps into the sky"' age = 18 money = 108.108108 print('Experienced' + str(age) + 'The test of time, I firmly believe' + message) # String connection print('Experienced%d The test of time, I firmly believe % s ' % (age, message)) # Formatting of strings # %d integer (decimal);% f floating point number;% s String:% x/x hexadecimal integer;% o octal integer print('Experienced%d,I firmly believe%s,Earned%.2f' % (age, message, money)) # %. 2f means floating point numbers retain two decimal places%. 3f means floating point numbers retain three decimal places print('Experienced%s,I firmly believe%s,Earned%s' % (age, message, money)) # In this case, string formatting automatically converts other data types to str
function
parameter
Formal parameters
Actual parameters
Common built-in functions
type(name) can be used to view the data type of variables;
id() can be used to find the location information of data in memory space;
input('prompt statement ') the information input to the console is of string type. If other types of data are required, the data type needs to be converted
The print function can input text, numbers, strings, expressions and files in a specified location
The input() function {receives input data from the user. The type of input data is str. a variable is needed to store this data
chr()
ord()
id() data storage location query
type() type query function
dir(math)
Return value of function
operator
Arithmetic operator
operator | describe | example |
---|---|---|
+ | plus | print(10+20) # 30 |
- | reduce | print(10-20) # -10 |
* | ride | print(10*5) #50 print(!*5) #!!!!! Ps: the string will be repeated many times when the number and string are multiplied |
/ | except | print(8/2) #4.0 |
// | Rounding | Return the integer part of quotient #5# print(11//2) #5# - print(-9//4) # - 3 |
% | Surplus | Returns the remainder of division #print(11%2) #1 |
** | index | a**b is the b power of a # print(2**10) #1024 |
() | parentheses | Increase operation priority #2 |
Ps: ① in mixed operation, the priority order is: * * higher than * /% / / higher than + -. In order to avoid ambiguity, it is recommended to use () to handle the operator priority.
② when different types of numbers are mixed, integers will be converted into floating-point numbers for operation.
③ if two strings are added, the two strings will be directly spliced into one string; If you add numbers and strings, you will directly report an error; If you multiply a number with a string, the string will be repeated many times.
Assignment Operators
1. Basic assignment operator
= | Assignment Operators | Assign the result on the right of the = sign to the variable on the left, such as num = 1 + 2 * 3, and the value of the result num is 7 |
Single variable assignment: number=10
Assignment of multiple variables: number1, number2 = 1, 2 (unpacking assignment of Series);
a = b =10; (chain assignment)
X, y = y, X (x, y exchange values)
Ps: the number of variables should correspond to the number of values one by one, otherwise assignment errors will occur
2. Compound assignment operator
operator | describe | example |
---|---|---|
+= | Additive assignment operator | c += a is equivalent to c = c + a |
-= | Subtraction assignment operator | c -= a is equivalent to c = c - a |
*= | Multiplication assignment operator | c *= a is equivalent to c = c * a |
/= | Division assignment operator | c /= a is equivalent to c = c / a |
//= | Integer division assignment operator | c //= a is equivalent to c = c // a |
%= | Modulo assignment operator | C% = a is equivalent to C = C% a |
**= | Power assignment operator | c **= a is equivalent to c = c ** a |
Ps: Note: the assignment operator operates from right to left and assigns the value on the right of the equal sign to the left of the equal sign. Therefore, the left of the equal sign must not be a constant or expression. Example: a + = 2 * 10 - > A = 2 * 10 + A
Logical operator
operator | Logical expression | describe | example |
---|---|---|---|
and | x and y | See false, false, all true is true When doing value calculation, take the first value as False. If all values are True, take the last value. | 1 and 2 and 3 -- > the result is 3 |
or | x or y | Seeing the truth is true, and all false is false When doing value calculation, take the first value that is True. If all values are False, take the last value. | 1 or 0 or 2 -- > the result is 1 |
not | not x | Boolean not - Returns False if x is True. If x is False, it returns True. | not (2and8) returns False |
a = 1 b = 2 c = 0 print(a and b) # 2 print(b and a) # 1 print(a or b) # 1 print(b or a) # 2 print(a or c) # 1 print(a and c) # 0 print(b or c) # 2 print(b and c) # 0 print(45 and 28 and 'hello' and 0) # 0 (take the first value that is False) print(0 or None) # None (if all values are False, take the last value.) print(0 or "" or None) # None (if all values are False, take the last value.)
Relational operator
( is ,< ,> ,<= ,>= ,!= ,==)
The result of a relational operator is a Boolean value
Ps: the '=' in the assignment operator, the '= =' in the comparison operator and the variable are composed of three parts: identification and numerical analysis
list1 = [11, 22, 33, 44] list2 = [11, 22, 33, 44] print(list1 == list2) # True print(list1, id(list1)) # [11, 22, 33, 44] 2126707372672 print(list2, id(list2)) # [11, 22, 33, 44] 2126707372224 print(list1 is list2) # False
Bitwise operator (-- operation for binary)
number1 = 6 number2 = 2 print(bin(number1), bin(number2)) # 0b110 0b10 print(number1 & number2) # 2 print(bin(number1 & number2)) # 0b10 # 0&0——>0; 0&1——>0; 1&0——>0; 1&1——>1; 1 is true, 0 is false, & similar to and; If the corresponding digits are 1, the result is 1, otherwise it is 0 print(number1 | number2) # 6 print(bin(number1 | number2)) # 0b110 # 0|1——>1; 1|1——>1; 0|0——>0; 1|0——>1; 1 is true, 0 is false, | similar to or; The corresponding digits are all 0, and the result digit is 0, otherwise it is 1 print(number1 ^ number2) # 4 print(bin(number1 ^ number2)) # 0b100 # The upper and lower numbers are the same, 0, and the difference is 1, ^ - > XOR number = 2 print(4 << number) # Moving number bits to the left is equivalent to multiplying by 2 to the power of number # Left shift operator < <, high overflow discard, low complement 0 print(4 >> number) # Moving number bits to the right is equivalent to dividing by 2 to the power of number # Shift right operator > >, low overflow discard, high complement 0 # ~Reverse; The basis for judging whether it is a negative binary. Look at the highest bit of the binary. If the highest bit is 1, it is a negative number, and if the highest bit is 0, it is a positive number print(~7) # Invert the binary of 7 - > - 8 # ~Decimal representation of 7: 1 Find binary 0000 0111 2 of + 7 first Inverse code 1111 1000 3 Complement 1111 1001 print(~-5) # Invert the binary of - 5 - > 4 # ~Decimal representation of - 5: 1 0000 0101——>: 2. Reverse: 1111 1010 - >: 3+ 1: 1111 1011 4. Reverse: 0000 0100 # Given the decimal negative number, find the binary negative number: 1 Original code of positive number 2 Reverse original code 3+ 1 - > binary representation of decimal negative numbers # [example] - 9 binary representation: 00001001 - > 11110110 - > 11110111 # Given the binary negative number, find the corresponding decimal representation: -- the decimal representation of binary negative number # 1. Binary negative 21 Binary - 1.3 Reverse 4 Original code: convert the original code into decimal and add it in front of decimal- # [example] decimal representation of 11111101: 1 Minus 1:1111 1100 2 Reverse: 0000 0011 3 Original code 0000 0011 4 Decimal: - 3
Comparison operator
operator | describe | Example (a = 1, B = 5) |
---|---|---|
== | Equals = whether the comparison objects are equal (comparison value) | (a == b) returns False |
!= | Not equal to} compares whether two objects are not equal | (a! = b) returns true |
<> | Not equal to} compares whether two objects are not equal | (a < > b) return true, similar= |
> | Greater than y returns whether x is greater than y | (a > b) returns False. |
< | Less than y returns whether x is less than y. The comparison operator returns 1 for True and 0 for False, which is equivalent to the variables True and False | (a < b) returns true. |
>= | Greater than or equal to y returns whether x is greater than or equal to y. | (a > = b) returns False. |
<= | Less than or equal to y returns whether x is less than or equal to y. | (a < = b) returns true. |
PS: ① the result of = = operation for numbers and strings is false. In addition to = = logical operation, errors will be reported directly.
② if two strings are compared, each character will be converted into the corresponding code, and then compared one by one.
str1='a' str2='ABC' # Convert the character into the corresponding code. The corresponding code of a is 97, and the corresponding code of a is 65 print(str1 > str2) #True
Operator precedence
The following table lists all operators from highest to lowest priority:
operator | describe |
---|---|
** | Index (highest priority) |
~ + - | Bitwise flip, unary plus and minus signs (the last two methods are named + @ and - @) |
* / % // | Multiplication, division, modulo and integer division |
+ - | addition and subtraction |
>> << | Shift right, shift left operator |
& | Bit 'AND' |
^ | | Bitwise Operators |
<= < > >= | Comparison operator |
<> == != | equal operator |
= %= /= //= -= += *= **= | Assignment Operators |
is is not | Identity operator |
in not in | member operator |
not>and>or | Logical operator |
# Priority of operation a = 1 b = 2 x = 20 print(b > a + x < a + b) # False print(b > a + (x < a + b)) # True print(a + False) # 1
Standard library
Third party Library
control structure
#Random number game import random computer=random.randint(1,6) guess=int(input('Please enter your guess:')) if computer==guess: print('Congratulations, you guessed right') else: print('Sorry, you guessed wrong') print('The correct answer is:',computer)
Sequential structure
Cyclic structure
for loop
# for item in range(start,stop,step) starts from start and ends at stop-1 by default # Use the for loop to print the cumulative sum of numbers between 1 and 100 sum = 0 for item in range(1, 101): sum += item print("sum =", sum) print("total_sum =", sum) # For... Else statement - if the above for loop 0~n-1 does not break, execute the else statement for i in range(3): username = input("enter one user name") password = input("Please input a password") if username == 'lx' and password == '123456': print('Login successful') break print('Incorrect user name or password!\n') else: print("Account locked")
while Loop
while Circular format n = 0 # initialize variable while n <= 10: # True - > enter the loop body print("The Dragon dives into the abyss and leaps into the sky") n += 2 # Change the self increase or self decrease of variable / variable print("*" * 5) # Print numbers from 1 to 50 that can be divided by 7 n = 1 count = 0 while n <= 50: if n % 7 == 0: print('Can be divided by 7——→', n) count += 1 n += 1 print('What can be divided by 7——→', count, 'individual') print("*" * 5) # The second method n = 0 while n <= 50 and n % 3 == 0: print("What can be divided by 7——→", n) n += 3 # Print the cumulative sum of numbers between 1 and 100 n = 0 sum = 0 while n <= 100: sum += n n += 1 print("n =", n, "sum =", sum) print("sum =", sum) print("*" * 5) # while... Else statement -- else statement, which is executed if not interrupted and not executed if interrupted n = 1 while n <= 10: print('n') n += 1 if n == 5: break else: print('over')
Ps: the difference between for loop and while loop
1. Definite and uncertain cycles
break statement
Format instance number = 0 while True: print('yeah') number += 1 if number == 5: break # Jump out of current loop structure # Enter the user name and password up to three times. If the login fails three times, you will be prompted that the account is locked for i in range(3): username = input("enter one user name") password = input("Please input a password") if username == 'lx' and password == '123456': print('Login successful') break print('Incorrect user name or password!\n') if i == 2: print("Account locked") # When shopping in the supermarket, you are allowed to buy multiple items and calculate the total price of goods total_money = 0 total_quantity = 0 while True: price = float(input('import value')) quantity = int(input('Enter quantity')) total_money += price * quantity total_quantity += quantity answer = input("total_money=%.2f,Continue(y/n)") if answer == "n": break print("total_quantity=%d,total_money=%.2f" % (total_quantity, total_money)) # Generate random numbers. You can guess them many times until you get it right. If you guess wrong, you will be prompted import random computer = random.randint(1, 10) count_game = 0 while True: guess = int(input("Please enter the number you guessed:")) count_game += 1 if guess == computer: print("Congratulations, you guessed right") break elif computer >= guess: print("Wrong guess, please guess bigger") else: print("Wrong guess, please guess smaller") print("You guessed%d second" % count_game) if count_game >= 5: print("Good luck. Keep up the good work") else: print("You're lucky. You're the emperor of Europe") print('— * - ' * 5)
continue Statement
Select structure / branch structure
if... elif... else module
Condition: operator composition, boolean type
Conditional statement
if condition 1:
Statement executed when condition 1 is True
elif condition n:
Statement executed when condition n is True
......
else:
The statement executed when none of the above conditions is true
# Generate two random integers of 0 ~ 10, and judge whether the sum of the two numbers is greater than 8 and the difference between the two numbers is less than 3. If yes, it displays: success; otherwise, it displays "fail" import random computer1 = random.randint(1, 10) computer2 = random.randint(1, 10) print("The two random numbers are,", computer1, computer2) if (computer1 + computer2 > 8) and (computer1 - computer2 < 3 and computer2 - computer1 < 3): # abs(computer1 - computer2) < 3 print('success') else: print('fail')
''' Alibaba merchant Festival, user name, total consumption amount, account amount, coupons Enter the total purchase amount If the amount is 0-500,then is lv1 Level, three free ones at random~10 A coupon of yuan; If 500-2000 Yuan is lv2,Two 50 yuan coupons will be presented. If you recharge, 10% of the recharge amount will be given%, 2000 Yuan or more lv3,Two 100 yuan coupons will be given away. If you recharge, 15 yuan will be given away%Amount of ''' user = "lx" total = 1500 # Total consumption amount money = 0 # Account amount coupon = 0 # coupon if 0 < total < 500: quan1 = random.randint(1, 10) quan2 = random.randint(1, 10) quan3 = random.randint(1, 10) coupon = quan1 + quan2 + quan3 elif 500 < total < 2000: coupon = 2 * 50 recharge = input('Recharge or not, 10% of the recharge amount%, y / n :\n') if recharge == "y": money += 1.1 * float(input("Please enter the recharge amount(element):")) elif total > 2000: coupon = 2 * 100 recharge = input('Recharge or not, 10% of the recharge amount%, y / n :\n') if recharge =='y': money += 1.15 * float(input("Please enter the recharge amount(element):"))
Nested loop of if
''' default username=admin,password=1234 Remember password bool Type, is_remember If the user name and password are correct, and is_remember yes True Means to remember the password, then print the password of the user who has been remembered, Otherwise, you don't remember the password when printing, and you need to continue to enter it next time ''' username=input('admin') password=input('1234') is_remember==True if username=='admin' and password=='1234': if is_remember: print('The user has been remembered%s Your password'%username) else: print('Failed to remember the password. You need to continue to enter it next time') else: print('Wrong user name or password!')
''' Simulated supermarket payment: 1.Enter the unit price and quantity of goods to calculate the total payable 2.Prompt the user to choose the payment method: no discount for cash payment, 95% discount for wechat payment, 20 less for card swiping over 100 ''' print('~~~~~~Welcome to Ziqiang supermarket~~~~~') price = float(input('Unit price of goods:')) number = int(input('Quantity of goods:')) total = price * number choice = input('Please select payment method: 1.Cash payment 2.Wechat payment 3.Card payment') if choice == '1': print('There is no discount for cash payment. The amount payable is:%.2f' % total) elif choice == '2': total = total * 0.95 print('Enjoy 95% discount on wechat payment,The payment amount is:%.2f' % total) elif choice == '3': if total > 100: total -= 20 print('Deduct 20 from 100 swiping card,The payment amount is:%.2f' % total) else: print('You can't enjoy the discount if your consumption is less than 100 ', total) else: print('Input error, please select again!')
if knowledge supplement
# Interval comparison of if statements a = 10 print(9 < a <= 21) # True print(11 < a < 20) # False # Ternary operator # Variable = value1 if condition else value2 when the condition holds, assign the value of value1 to the variable; otherwise, assign the value of value2 to the variable a=10 b=30 c=a if a>b else b print('a and b The larger of the two numbers is',c) # Automatic conversion type '''if Statement needs a judgment condition, and the result of this judgment condition needs a Boolean value, If the judgment condition entered at this time is not a Boolean value, this value will be automatically converted into a Boolean value during code execution''' if 'hello': print('hello world!') else: print('Life is too short for me to learn Python') '''stay Python There are only empty strings in the'',"",'''''',Number 0, empty dictionary{},Empty list[],Empty tuple(), And null data None Will be converted into False,Everything else will be converted into True'''
object
Assignment semantics
Reference semantics
4, Library call
import keyword
print(keyword.kwlist)
list
1. Features of the list:
① Order
② An index corresponds to a list element, but a list element has two indexes
③ The list can store any type of data
④ List elements can be repeated
2. List creation
name=[]; name=list()
List generating formula (formula for generating list)
[i*i for i in range(start,stop,step)] (represents related expressions, user-defined variables and iteratable objects of list elements)
Note: = expressions representing list elements usually contain custom variables
3. List query
The index() function returns only the first element index of the same element if there are multiple identical elements in the list; If the queried element does not exist in the list, ValueError will be thrown; You can also find between the specified start and stop
Gets a single element in the list
Get multiple elements in the list
Forward index} from 0 to N-1
Reverse index {from - N to - 1
Specify index
Judge whether the specified element is in the list or not
Traversal for iteration variable in list name
4. Slicing a list -- getting multiple elements in a list
[start,stop,step]
5. List modification
Add operation
append() adds an element to the end of the list
extend() adds at least one element to the end of the list
insert() adds an element anywhere in the list
Add at least one element anywhere in the list
list = [10, 20, 30] print('Before adding elements', type(list)) # < class' list '> before adding elements list.append(100) print('After adding elements', list, type(list)) # After adding elements [10, 20, 30, 100] < class' list '> list[2:] = [80, 90] print('After the second modification', list) # After the second modification [10, 20, 80, 90]
Delete operation
remove() Deletes one at a time; Delete only the first duplicate element; Throw an exception if the element does not exist
pop() deletes an element at a specified index position; The specified index does not exist, and an IndexError is thrown; Deletes the last element in the list without specifying an index
clear() clear the list
del() delete list
The slice deletes at least one element at a time
Modification of list values
Modify one value at a time # list[index]=value
Modify multiple values at one time, such as list[start,stop,step]=[value1,value2,value3...]
6. Sorting of lists
Specify keyword parameters
reverse=False = ascending
reverse=True descending sort
Call the sort() method. By default, all elements in the list are sorted in descending order. You can specify reverse=True to sort in descending order
Call the built-in function sorted() to specify reverse=True to sort in descending order. Do not change the list
tuple
Dictionaries
recursion
Components of recursion
Recursive call
Recursive termination condition
Recursive call procedure
Every time the function is called recursively, a stack frame will be allocated in the stack memory; Each time the function is executed, the corresponding space will be released
Advantages and disadvantages of recursion
Disadvantages: it takes up too much memory and is inefficient
Advantages: simple thinking and code
File processing
File format: mp4,. mp3,txt., md et al
File path