Conditional judgment
A Python conditional statement is a block of code that determines execution by the execution result (True or False) of one or more statements.
You can easily understand the execution process of the conditional statement through the following figure:
The Python programming language specifies that any non-zero and non-null (null) value is true, and 0 or null is false.
In Python programming, the if statement is used to control the execution of the program. The basic form is:
1 | if judgment condition: execute statement... else: execute statement... |
When the "judgment condition" is established (non-zero), the following statement is executed, and the execution content can be multiple lines, which are distinguished by indentation to indicate the same range.
else is an optional statement, and the related statement can be executed when the content needs to be executed when the condition is not established.
GIF demo:
example:
1 | #!/usr/bin/python # - *- coding: UTF-8 - *- # Example 1: Basic usage of if flag = False name = 'luren' if name == 'python': # Determine if the variable is python flag = True # set the flag to true when the condition is true print 'welcome boss' # and print welcome message else: print name # Output variable name when condition is not true |
output:
luren # output result
The judgment conditions of the if statement can be represented by > (greater than), < (less than), == (equal to), >= (greater than or equal to), and <= (less than or equal).
When the judgment condition has multiple values, the following forms can be used:
1 | if judgment condition 1: Execute statement 1... elif Judgment Condition 2: Execute statement 2... elif Judgment Condition 3: Execute statement 3... else: Execute statement 4... |
where elif
is short for elseif
.
example:
1 | #!/usr/bin/python # - *- coding: UTF-8 - *- # Example 2: elif usage num = 5 if num == 3: # Determine the value of num print 'boss' elif num == 2: print 'user' elif num == 1: print 'worker' elif num < 0: # output if the value is less than zero print 'error' else: print 'roadman' # output when none of the conditions are met |
output:
Comment first then view it after your comment is approved. Join QQ Group to display all hidden texts.
Since python does not support switch statements, multiple conditional judgments can only be implemented with elif. If the judgment requires multiple conditions to be judged at the same time, you can use or (or), which means that the judgment condition is successful when one of the two conditions is established. ; When using and (and), it means that the judgment condition is successful only if the two conditions are met at the same time.
1 | #!/usr/bin/python # - *- coding: UTF-8 - *- # Example 3: if statement with multiple conditions num = 9 if num >= 0 and num <= 10: # Determine if the value is between 0 and 10 print 'hello' # output result: hello num = 10 if num < 0 or num > 10: # Determine whether the value is less than 0 or greater than 10 print 'hello' else: print 'undefined' # output result: undefined num = 8 # Determine whether the value is between 0~5 or 10~15 if (num >= 0 and num <= 5) or (num >= 10 and num <= 15): print 'hello' else: print 'undefined' # output result: undefined |
When if has multiple conditions, parentheses can be used to distinguish the order of judgment. The judgments in parentheses are executed first. In addition, the priority of and and or is lower than the judgment symbols such as > (greater than) and < (less than), that is, greater than and less than In the absence of parentheses, it will take precedence over and or.
cycle
To calculate 1+2+3, we can write the expression directly:
1 | >>> 1 + 2 + 3 6 |
To calculate 1+2+3+...+10, I can barely write it.
However, to calculate 1+2+3+...+10000, it is impossible to write the expression directly.
In order for a computer to compute thousands of repetitions, we need loops.
For loop
There are two kinds of loops in Python. One is the for...in loop, which iterates each element in the list or tuple in turn. See the example:
1 | names = ['Michael', 'Bob', 'Tracy'] for name in names: print(name) |
Executing this code will print each element of names
in turn:
Comment first then view it after your comment is approved. Join QQ Group to display all hidden texts.
So the for x in ...
loop is to substitute each element into the variable x, and then execute the statement of the indented block.
For another example, if we want to calculate the sum of integers 1-10, we can use a sum variable for accumulation:
1 | sum = 0 for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]: sum = sum + x print(sum) |
If you want to calculate the sum of integers from 1-100, it is a bit difficult to write from 1 to 100.
Python provides a range()
function that generates a sequence of integers.
range(101)
can generate a sequence of integers from 0-100, calculated as follows:
1 | sum = 0 for x in range(101): #Because it is generated from 0, it is the 101st number when it is generated to 100 sum = sum + x print(sum) |
While loop
As long as the conditions are met, the loop continues, and when the conditions are not met, the loop is exited. For example, if we want to calculate the sum of all odd numbers within 100, we can use a while loop to achieve:
1 | sum = 0 n = 99 while n > 0: sum = sum + n n = n - 2 print(sum) |
The variable n
inside the loop is continuously decremented until it becomes -1
, the while condition is no longer satisfied, and the loop exits.
Break function
In a loop, the break
statement can exit the loop early. For example, to print the numbers from 1 to 100 in a loop:
1 | n = 1 while n <= 100: print(n) n = n + 1 print('END') |
The above code can print out 1~100.
If you want to end the loop early, you can use the break
statement:
1 | n = 1 while n <= 100: if n > 10: # When n = 11, the condition is satisfied, execute the break statement break # break statement will end the current loop print(n) n = n + 1 print('END') |
Execute the above code, you can see that after printing 1~10, END
is printed immediately, and the program ends.
It can be seen that the function of break
is to end the loop early.
Continue function
During the loop, you can also use the continue
statement to skip the current loop and start the next loop directly.
1 | n = 0 while n < 10: n = n + 1 print(n) |
The above program can print out 1 to 10. However, if we want to print only odd numbers, we can skip certain loops with the continue
statement:
1 | n = 0 while n < 10: n = n + 1 if n % 2 == 0: # If n is even, execute continue statement continue # The continue statement will directly continue the next cycle of the loop, and the subsequent print() statement will not be executed print(n) |
Execute the above code, you can see that the print is no longer 1 to 10, but 1, 3, 5, 7, 9.
It can be seen that the function of continue
is to end the current cycle in advance and directly start the next cycle.
summary
Loops are an efficient way to get a computer to do repetitive tasks.
The break
statement can directly exit the loop during the loop, and the continue
statement can end the current loop early and directly start the next loop. Both of these statements must usually be used with an if
statement.
Take special care not to abuse the break
and continue
statements. break
and continue
will cause too many logical forks of code execution, which are prone to errors. Most loops do not need break
and continue
statements. In the above two examples, you can remove break
and continue
statements by rewriting the loop condition or modifying the loop logic.
Sometimes, if the code is written incorrectly, it will cause the program to fall into an "infinite loop", that is, to loop forever. At this point, you can use Ctrl+C to exit the program, or force the end of the Python process.
Thanks
Reprinted from:
Zeruns's Blog
Python theoretical knowledge(3)Conditions and Loops
Comments