conditions, loops, and other statements
Use of Import
The standard syntax for import is:
Import module1[,module2[,... Modulen]]
Indicates that an import is allowed to import multiple modules, but each module needs to be separated by commas.
When the interpreter encounters an import statement, the module is imported if it is in the current search path. The search path is an interpreter that searches the list of all directories first.
The Python search path consists of a list of directory names that the Python interpreter will look for in turn to introduce modules.
The search path is determined at the time of Python compilation or installation and is stored in the variable of path of the SYS module
The way to see the Python default search path is as follows:
Import sysprint (' python default search path:%s '%sys.path)
C:\python\python.exe c:/python.py/tiaojianxunhuanyuju.py
The default search path for Python is: [' c:\\python.py ', ' c:\\python.py ', ' c:\\python\\python35.zip ', ' c:\\python\\dlls ', ' c:\\python\\lib ', ' C:\\python ', ' c:\\python\\lib\\site-packages ']
From the above can be to Sys.path output is a list, the first output is the directory where the executable file, that is, the Python interpreter directory
In addition to the import statement Introduction module, you can also use the FROM statement to introduce modules.
The FROM statement can import the specified part from the module to the current namespace.
The form syntax is as follows:
From modname import name1[,name[,... name]]
For example:
From math import piprint (PI)
C:\python\python.exe c:/python.py/tiaojianxunhuanyuju.py
3.141592653589793
The previous example is to import the PI from the math module into the current namespace, which does not import the entire module of math.
Import and from are a comparison: (Take sin, exp, pi in the Math module for example)
Import Statement Example:
Import Mathprint (Math.PI) print (Math.sin (1)) Print (Math.exp (1))
C:\python\python.exe c:/python.py/tiaojianxunhuanyuju.py
3.141592653589793
0.8414709848078965
2.718281828459045
From the above, we can see that the import function is output after importing the math module.
From Statement Example:
From math import piprint (pi) print (sin (1))
C:\python\python.exe c:/python.py/tiaojianxunhuanyuju.py
Traceback (most recent):
3.141592653589793
File "c:/python.py/tiaojianxunhuanyuju.py", line 9, <module>
Print (sin (1))
Nameerror:name ' sin ' is not defined
It can be seen from the above that the FROM statement specifies the PI function of the math module and the other functions in math cannot be output.
The benefits of using the FROM statement are as follows:
Import Mathprint (Math.PI) print (PI)
C:\python\python.exe c:/python.py/tiaojianxunhuanyuju.py
Traceback (most recent):
3.141592653589793
File "c:/python.py/tiaojianxunhuanyuju.py", line 9, <module>
Print (PI)
Nameerror:name ' pi ' is not defined
It can be seen from the above that accessing the Pi object when importing the math module using the Impot statement requires the use of Math.PI or an error
From math import piprint (PI)
C:\python\python.exe c:/python.py/tiaojianxunhuanyuju.py
3.141592653589793
It can be seen from the above that the Pi object can be accessed directly after using the FROM statement, without the need to add the module name
The FROM statement can import multiple functions in a single statement, and multiple functions are separated by commas.
For example:
From math import pi,sin,exp
You can also import all the functions in a module.
For example:
From Math Import *
Note: The FROM statement does not recommend excessive use in the actual development environment and is not conducive to writing clear, simple code. Use this method only if you want to import all features from a given module.
Import statement to alias a module
For example:
Import math as Mprint (M.PI)
C:\python\python.exe c:/python.py/tiaojianxunhuanyuju.py
3.141592653589793
To alias a module is to add an as clause at the end of the statement at the export module, followed by an alias name.
The FROM statement takes an alias to the module ibid.
For example:
From Math import pi as Pprint (p)
C:\python\python.exe c:/python.py/tiaojianxunhuanyuju.py
3.141592653589793
Use a comma output
Use the comma output example:
Name= ' Du Yuheng ' print (' I'm called: ', name)
C:\python\python.exe c:/python.py/tiaojianxunhuanyuju.py
My name is: Du Yuheng
You can also use commas to output multiple expressions, as long as you separate multiple expressions with commas!
AA = ' Hello everyone! ' BB = ' My name is Du Yuheng, ' cc = ' from Beijing. ' Print (AA,BB,CC)
C:\python\python.exe c:/python.py/tiaojianxunhuanyuju.py
Hello everyone! My name is Du Yuheng, from Beijing.
Different re-assignment values
Sequence Unpacking
Multiple assignment operations are performed at the same time.
For example:
X, z = 1,2,3print (x, Y, z)
C:\python\python.exe c:/python.py/tiaojianxunhuanyuju.py
1 2 3
Swaps the values of two or more variables.
X, y, z = 1,2,3x,y = Y,xprint (x, Y, z)
C:\python\python.exe c:/python.py/tiaojianxunhuanyuju.py
2 1 3
The output of the above example shows that the values of x and Y are exchanged
In Python, what the Exchange does is called a sequence unpacking (sequence unpacking) or an optional iterative solution that unlocks a sequence of multiple values and then puts it into a sequence of variables.
For example:
num = 1,2,3print (' original value: ', num) x, y, z = numprint (' Get Sequence untied Value (x): ', x) print (' Get sequence all untied values: ', x, Y, z)
C:\python\python.exe c:/python.py/tiaojianxunhuanyuju.py
Original value: (1, 2, 3)
Get the sequence untied value (x): 1
Get the sequence of all untied values: 1 2 3
You can use the Popitem method to return a key-value as a tuple, and the returned tuple can be directly assigned to a value of two variables.
For example:
Student = {' name ': ' Du Yuheng ', ' number ': ' 666 '}key,value=student.popitem () print (key) print (value)
C:\python\python.exe c:/python.py/tiaojianxunhuanyuju.py
Name
Du Yuheng
The sequence unpacking allows the function to return more than one value and package the Narimoto group and then access it through an assignment clause.
Note: The number of elements in the unpacking sequence must be exactly the same as the number placed on the left side of the assignment symbol "=".
Chained assignment
Assigning a value to multiple variables by multiple equations is called chained assignment.
For example:
X=y=z=10print (x) print (y) print (z)
C:\python\python.exe c:/python.py/tiaojianxunhuanyuju.py
10
10
10
Chained assignment is the assignment of the same value to multiple variables.
You can also assign values individually
For example:
X=10y=xprint (y)
C:\python\python.exe c:/python.py/tiaojianxunhuanyuju.py
10
It is obvious that the chain value is concise when the individual assignment is compared with the chain assignment.
Increment assignment
Place the expression on the left side of the assignment operator (=) (such as x=x+1 as X+=1), which is called an incremental assignment (augemented assignment).
This notation is appropriate for the +-*/% flag operators.
For example:
X=5x+=1print (' Plus ', x) x-=2print (' minus ', x) x*=2print (' Multiply ', x) x/=4print (' except ', x)
C:\python\python.exe c:/python.py/tiaojianxunhuanyuju.py
Plus 6
Minus 4
by 8
Except 2.0
Using the incremental assignment relative assignment operation looks more concise.
The increment assignment applies to the data type of the two-dollar operator in addition to the numeric type.
For example:
Name= ' Du Yuheng, ' name+= ' 666 ' Print (name) name*=2print (name)
C:\python\python.exe c:/python.py/tiaojianxunhuanyuju.py
Du Yuheng, 666
Du Yuheng, 666 Du Yuheng, 666
Statement block
In Python, a colon (:) is used to identify the beginning of a statement block, and each statement in a statement block needs to be indented (the same amount is indented). When you return to the same indent as an already closed block, the current statement block has ended.
Conditional statements
If statement
Basic usage of IF
For example:
greeting = ' Hello ' if greeting = = ' Hello ': print (' Hello ')
C:\python\python.exe c:/python.py/tiaojianxunhuanyuju.py
Hello
If the condition (an expression between an if colon) is determined to be true, the subsequent statement block is executed: if the condition is determined to be false, the statement block will not be executed.
If blocks can be composed of multiple statements, the writing process should be careful to maintain the consistency of the statement indentation.
For example:
greeting = ' Hello ' if greeting = = ' Hello ': student={' Du Yuheng ': ' 666 ', ' Gao ': ' 777 ', ' Xu Wei ': ' 888 ', ' Du Chaoli ': ' 999 '} print (' There are%d elements in the dictionary ') %len (student)) Student.clear () print (' number of elements after dictionary deletion:%d '%len (student) ')
C:\python\python.exe c:/python.py/tiaojianxunhuanyuju.py
Hello
There are 4 elements in the dictionary
The number of elements after a dictionary deletion is: 0
In addition to using the = =, the condition of the IF statement can also use a conditional representation size relationship of > (greater than), < (less than), >= (greater than or equal), <= (less than equals), and so on.
You can also use each function or method return value as a condition determination.
ELSE clause
Basic usage of Else
For example:
Greeting = ' Hi ' if greeting = = ' Hello ': print (' Hello ') else:print (' the statement block is not in if, the value of greeting is not hello ')
C:\python\python.exe c:/python.py/tiaojianxunhuanyuju.py
The statement block is not in the IF, the value of greeting is not a hello
This procedure adds a new conditional clause to the--ELSE clause, which is called a clause because else is not a standalone statement, only as part of the IF statement. Use the ELSE clause to add a choice.
Note: There is no conditional decision after the ELSE clause
elif clause
Basic usage of elif clauses
For example:
num = 10if num > 10:print (' num ' value is greater than ten ') Elif 0 <=num<=10:print (' num values from 0 to 10 ') else:print (' num ' value is less than 0 ')
C:\python\python.exe c:/python.py/tiaojianxunhuanyuju.py
Num has a value between 0 and 10
It is shown from the output that this program executes the block of statements in the ELIF clause, that is, the condition of the ELIF clause evaluates to TRUE, so the statement block after the clause is executed.
Elif need to be used in conjunction with an IF, else clause, cannot be used independently, and must begin with an if statement, optionally ending with an else clause.
Nested code blocks
Nested code block nested code block is to put If,else, elif and other conditional statements into if, Slse, elif conditional statement block, as a deep-seated conditional judgment statement.
Basic usage of nested code blocks
For example:
num = 10if num%2 = = 0:if num%3 = 0:print ("The number you enter can be divisible by 2 and 3") elif num% 4 = = 0:print ("The number you enter can be divisible by 2 and 4 Else:print ("The number you enter can be divisible by 2, but not divisible by 3 and 4") else:if num% 3 = = 0:print ("The number you enter can be divisible by 3, but not divisible by 2") Else: Print ("The number you enter cannot be divisible by 2 and 3")
C:\python\python.exe c:/python.py/tiaojianxunhuanyuju.py
The number you enter can be divisible by 2, but not divisible by 3 and 4.
As you can see from the previous example, if statements, statement blocks, and ELSE clauses exist in the statement block of an if statement, the IF and else clauses can also exist in the statement block of the ELSE clause.
Is
is: identity operator
Basic usage of IS
For example:
X=y=[1,2,3]z=[1,2,3]print (x==y) print (x==z) print (x is y) print (x is Z)
C:\python\python.exe c:/python.py/tiaojianxunhuanyuju.py
True
True
True
False
As you can see from the previous example, the x and Z are equal. This is the argument that the variable x and Y are bound to the same list, and the variable z is bound to another list with the same values and order. Their values may be equal, but they are not the same object.
Use the = = operator to determine whether two objects are equal, using is to determine whether two objects are the same (whether the same object).
Comparing strings and sequences
To compare a list
For example:
Print ([1,2]<[2,1]) print ([1,2]<[1,2]) print ([1,2]==[1,2])
C:\python\python.exe c:/python.py/tiaojianxunhuanyuju.py
True
False
True
Comparison rules also apply to sequence elements
For example:
Print ([2,[1,2]]<[2,[1,3]])
C:\python\python.exe c:/python.py/tiaojianxunhuanyuju.py
True
Boolean operator
The AND operator is used to concatenate two Boolean values, and both of them are true, or false otherwise.
For example:
num = 10if num <=10 and num>=5:print (' num ' value between 5 and 10 ') else:print (' num ' value is not from 5 to 10 ')
C:\python\python.exe c:/python.py/tiaojianxunhuanyuju.py
Num has a value between 5 and 10
And the same as and and not a single operator
Attribute of Boolean: evaluates only if a value is required.
Boolean operators are often referred to as logical operators, and the same behavior applies to or. For example, in an expression x or Y, X returns the value of x directly, otherwise it returns the value of Y. This means that the code after the Boolean operator is not executed.
Assertion
The following points need to be noted when using assertions:
The ①assert assertion is used to declare that a condition is true.
② If you are very sure that you have at least one element in the list you are using and want to test this and throw an error when it is not true, then the Assert statement is the ideal statement to apply in this case.
A assertionerror is raised when the ③assert statement fails.
For example:
X=3assert x > 0, ' x is not zero or negative ' #提示x不是偶数assert x% 2 ==0, ' X was not a even number '
C:\python\python.exe c:/python.py/tiaojianxunhuanyuju.py
Traceback (most recent):
File "c:/python.py/tiaojianxunhuanyuju.py", line 8, <module>
Assert x% 2 ==0, ' x is not a even number '
Assertionerror:x is isn't an even number
As can be seen from the above example, when the condition after the assert is true, the program runs normally, and when the condition after the assert is false, the error message is output and the error message is customized, and this error message can be called an exception parameter. The exception argument for an assert is the string information that is added after the assertion expression to explain the assertion and to know more easily where the problem is.
Cycle
While loop
The basic syntax for the while loop is as follows:
While judging condition:
Execute statement ...
The execution statement can be a single statement or a block of statements. The judging condition can be any expression, and all non-0, non-null (NULL) values are true (true). When the judgment statement is False (false), the loop is ended.
Small example:
Use the simple program output to all the numbers as follows:
N=1while N < 6:print ("Current number is:", N) n+=1
C:\python\python.exe c:/python.py/tiaojianxunhuanyuju.py
The current number is: 1
The current number is: 2
The current number is: 3
The current number is: 4
The current number is: 5
For loop
The syntax format for the For loop is as follows:
For Iterat_var in sequence:
Statements (s)
Sequence is an arbitrary sequence, and Iterat_var is the element that needs to be traversed in the sequence. Statements is the block of statements to be executed.
To loop a string for:
For letters in ' good ': print (' current ', letter)
C:\python\python.exe c:/python.py/tiaojianxunhuanyuju.py
Current Letter G
Current Letter O
Current Letter O
Current Letter D
To loop a sequence of numbers
Number =[1,2,3]for num in number:print (' current digit ', num)
C:\python\python.exe c:/python.py/tiaojianxunhuanyuju.py
Current Number 1
Current number 2
Current number 3
A For loop for a dictionary
Name = {' name ': ' Du Yuheng ', ' number ': ' 666 '}for tup in Name:print ('%s:%s '% (Tup,name[tup]))
C:\python\python.exe c:/python.py/tiaojianxunhuanyuju.py
Name: Du Yuheng
number:666
Looping through dictionary elements
Use the items method to return key-value pairs as tuples.
For example:
Name = {' name ': ' Du Yuheng ', ' number ': ' 666 '}for Key,value in Name.items ():
C:\python\python.exe c:/python.py/tiaojianxunhuanyuju.py
Name: Du Yuheng
number:666
The elements in the dictionary are not sequential. In other words, the keys and values in the iteration dictionary are guaranteed to be processed, but the processing order is indeterminate, which is why the output of the elements in the dictionary is not sequentially output with a for loop;
Iterative Tools
Parallel iterations:
A program can iterate over two sequences.
For example:
Student =[' Duyuheng ', ' Xuwei ', ' gaoshuan ']number = [' 666 ', ' 777 ', ' 888 ']for i in range (len (student)): print (Student[i], ' School number is ', number[i])
C:\python\python.exe c:/python.py/tiaojianxunhuanyuju.py
Duyuheng's school number is 666.
Xuwei's school number is 777.
Gaoshuan's School number is 888.
In the program above, I is the standard variable name for a circular index.
You can also use the built-in function zip for parallel iterations, merging two sequences together to return a list of tuples.
For example:
Student =[' Duyuheng ', ' Xuwei ', ' gaoshuan ']number = [' 666 ', ' 777 ', ' 888 ']for name,num in Zip (student,number): Print (name, ' The number is: ', num)
C:\python\python.exe c:/python.py/tiaojianxunhuanyuju.py
Duyuheng's number is: 666
Xuwei's number is: 777
Gaoshuan's number is: 888
The ZIP function can operate on any number of sequences and can cope with unequal sequences that stop when the short sequence "runs out".
For example:
For num1,num2 in Zip (range (3), range): Print (' Zip key value pair is ', num1,num2)
C:\python\python.exe c:/python.py/tiaojianxunhuanyuju.py
Zip key value pair is 0 0
Zip key value pair is 1 1
Zip key value pair is 2 2
As can be seen from the output, the ZIP function takes a short sequence, and when the short sequence traversal is finished, the For loop ends the traversal.
Flip and sort iterations
The reversed and sorted functions can be used for any sequence or iterative object, but instead of modifying the object in situ, it returns a flipped or sorted version.
For example:
Print (sorted ([2,3,4,1,5])) print (sorted (' hello,world! ')) Print (List (Reversed (' hello,world! '))) Print (". Join" (Reversed (' hello,world! ')))
C:\python\python.exe c:/python.py/tiaojianxunhuanyuju.py
[1, 2, 3, 4, 5]
['! ', ', ', ' d ', ' e ', ' h ', ' l ', ' l ', ' l ', ' o ', ' o ', ' R ', ' W ']
['! ', ' d ', ' l ', ' r ', ' O ', ' w ', ', ', ' o ', ' l ', ' l ', ' e ', ' H ']
!dlrow,olleh
As you can see from the output, the sorted function returns a list, and the reversed function returns an object that can be iterated. There is no problem with using the For loop and the Join method. If you need to use indexes, shards, and call the list method on both functions, you can use the list type transformation to return the object.
Jump out of the loop
Break
The break statement is used to terminate the loop statement, even if there is no false condition in the loop condition or the sequence has not finished traversing.
The break statement is used in the while and for loops.
If a nested loop is used, the break statement stops executing the deepest loop and starts executing the next line of code.
When a break statement is encountered, no matter what the condition, it jumps out of the loop.
For example:
#for示例for letters in ' Hello ': if letters = = ' L ': Break print (' The current letter is: ') #while循环num = 10while num > 0: Print (' Output number: ', num) num-= 1 if num = = 8:break
C:\python\python.exe c:/python.py/tiaojianxunhuanyuju.py
The current letter is: H
The current letter is: E
Output numbers are: 10
Output numbers are: 9
The For loop example shows that the output statement output loops through the characters and jumps out of the for loop when the specified character is encountered.
When you use while to make a conditional decision, the number that satisfies the condition is output in the statement block, and when the number equals the specified number, it jumps out of the while loop and no longer iterates.
Continue
The continue statement is used to tell Python to skip the remaining statement of the current loop, and then proceed to the next round loop.
When a continue statement is encountered during execution, regardless of whether the execution condition is true or false, it is necessary to jump out of the loop and into the next loop.
For example
#for示例for letters in ' Hello ': if letter = = ' L ': Continue print (' current ': ', letter ') #while示例num = 3while num > 0: num-= 1 if num = = 2:continue print (' Current variable value: ', num)
C:\python\python.exe c:/python.py/tiaojianxunhuanyuju.py
Current Letter: H
Current Letter: E
Current Letter: O
Current variable Value: 1
Current variable Value: 0
As can be seen from the above example, using the Continue statement knowledge skips a loop and does not jump out of the loop, compared to the break statement.
Else clause in a loop
Using the Else statement in a while loop
When the while condition statement is false, the statement block of else is executed.
For example:
num = 0while num < 3:print (num, "less than 3") num + = 1else:print (num, "greater than or equal to 3") print ("End loop!!!") ")
C:\python\python.exe c:/python.py/tiaojianxunhuanyuju.py
0 less than 3
1 less than 3
2 Less than 3
3 is greater than or equal to 3
End Loop!!!
As you can see from the output, the statement block in the Else statement was executed after the while loop, and the statement "3 greater than or equal to 3" was output.
Using the Else statement in a for loop
Executes the statement block of else if the for condition statement is false or if no break is interrupted after the end.
For example:
names = [' Duyuheng ', ' Duzhaoli ']for name in Names:if name = = "Du": Print (' name: ', name ') Break print ("Loop Name column Table "+name" Else:print ("No looping data!") ") Print (" End loop! ") ")
C:\python\python.exe c:/python.py/tiaojianxunhuanyuju.py
Circular Name List Duyuheng
Circular Name List Duzhaoli
No looping data!
End Loop!
The output condition sees that the for loop finishes after the content in the Else statement block is executed.
Pass Statement
The pass in Python is an empty statement that preserves the integrity of the program structure.
Basic usage of PASS statement:
name = ' Duyuheng '
If name = = ' Duyuheng ':
Print (' Hello ')
elif name = = ' Duzhaoli ':
Pass
Else
Print (' Nothing ')
C:\python\python.exe c:/python.py/tiaojianxunhuanyuju.py
Hello
If you don't use pass placeholder, you'll get an error.
This article from "Duyuheng" blog, declined reprint!
Handbook of python3.5 cultivation 11