Conditional and Loop Statements
4 Conditional and Looping Statements
4.1 if statement
- Expr_of if statement True_ A suite block of code executes only if the conditional expression expression result is true, otherwise execution continues immediately following it
Statement after the code block. - The expression conditional expression in a single if statement can achieve multiple conditional judgments through Boolean operators and, or, and not.
if expression: expr_true_suite if 2 > 1 and not 2 > 3: print('Correct Judgement!') # Correct Judgement!
4.2 if - else statement
- Python provides an else to use with if, and if the conditional expression of the if statement results in a false Boolean value, the program executes the code after the else statement.
- If statements support nesting, that is, embedding another if statement in one if statement to form different levels of selection structure. Python uses indentation rather than braces to mark code block boundaries, so pay special attention to else dangling.
if expression: expr_true_suite else expr_false_suite
4.3 if - elif - else statement
- An elif statement is else if, which checks if multiple expressions are true and executes code in a specific block of code when true.
temp = input('Please enter your results:') source = int(temp) if 100 >= source >= 90: print('A') elif 90 > source >= 80: print('B') elif 80 > source >= 60: print('C') elif 60 > source >= 0: print('D') else: print('Input error!')
4.4 assert keywords
- assert is a keyword we call assertion. When the condition behind this keyword is False, the program crashes and throws
An exception to AssertionError was thrown. - When unit testing, it can be used to place checkpoints in the program, and only if the condition is True can the program work correctly.
assert 3 > 7 # AssertionError
5 Loop statement
5.1 while Loop
- The most basic form of a while statement consists of a Boolean expression at the top and one or more indented statements belonging to the while code block.
- The code block of the while loop loops until the Boolean expression has a Boolean false value.
- If a Boolean expression does not have <, >, ==,!=, Operators such as in, not in, and so on, which only give conditions such as numeric values, are also possible. Write after while
When a non-zero integer is entered, it is treated as a true value and the loop is executed. When 0 is written, it is treated as a false value and the loop is not executed. You can also write str, list, or any order
Columns with non-zero length are treated as true values and loop body is executed. Otherwise, it is considered false and the loop is not executed.
count = 0 while count < 3: temp = input("You might as well guess what the little brother is thinking about now:") guess = int(temp) if guess > 8: print("Big, big") else: if guess == 8: print("Are you the Ascaris in your little brother's heart?") print("Hum, guess right and no reward!") count = 3 else: print("Small, small") count = count + 1 print("The game is over, don't play!")
5.2 while - else cycle
When the while loop has finished executing normally, execute the else output. If a statement that jumps out of the loop, such as break, is executed in the while loop, it will not persist
Line else code block content.
count = 0 while count < 5: print("%d is less than 5" % count) count = 6 break else: print("%d is not less than 5" % count) # 0 is less than 5
5.3 for loop
- The for loop is an iteration loop, which is equivalent to a general sequence iterator in Python and can traverse any ordered sequence, such as str, list, tuple, etc.
Any Iterable object, such as dict, can be traversed. - For each loop, the iteration variable is set to the current element of an Iterable object and is provided to the code block for use.
for Iteration variable in Iterable Objects: code block for i in 'ILoveLSGO': print(i, end=' ') # No Line Break Output # I L o v e L S G O
5.4 for - else loop
When the for loop completes normally, execute the else output, and if a statement that jumps out of the loop, such as break, is executed in the for loop, it will not persist
Line the contents of the else code block, as in the while - else statement.
for Iteration variable in Iterable Objects: code block else: code block
5.5 range() function
range([start,] stop[, step=1])
- This BIF (Built-in functions) has three parameters, two of which are enclosed in square brackets to indicate that the two parameters are optional.
- step=1 means that the default value for the third parameter is 1.
- range is a BIF that generates a sequence of numbers starting with the value of the start parameter and ending with the value of the stop parameter that contains the start's
Value without stop.
for i in range(1, 10, 2): print(i) # 1 # 3 # 5 # 7 # 9
5.6 enumerate() function
enumerate(sequence, [start=0])
- Sequence - A sequence, iterator, or other object that supports iteration.
- Start - The start position of the subscript.
- Returns an enumerate object
Combined use of enumerate() and for loop
Using enumerate(A) not only returns the element in A, but also gives it an index value (starting with 0 by default). In addition, use
enumerate(A, j) can also determine the starting value of the index is J.
5.7 break statement
The break statement can jump out of the loop at the current layer.
5.8 continue statement
continue terminates this cycle and begins the next.
for i in range(10): if i % 2 != 0: print(i) continue i += 2 print(i) # 2 # 1 # 4 # 3 # 6 # 5 # 8 # 7 # 10 # 9
5.9 pass statement
- The pass statement means "do nothing". If you don't write anything where you need it, the interpreter will indicate an error, and the pass statement will
Is used to solve these problems. - Pass is an empty statement that does nothing but occupies a space to maintain the integrity of the program structure. Although pass statements do not do anything
Yes, but if you're not sure what code to put in one place for the time being, you can put a pass statement first so that the code works properly.
def a_func(): # SyntaxError: unexpected EOF while parsing def a_func(): pass
5.10 Derivation
List Derivation
[ expr for value in collection [if condition] ]
x = [[i, j] for i in range(0, 3) for j in range(0, 3)] print(x) # [[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]] x[0][0] = 10 print(x) # [[10, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]
Tuple derivation
( expr for value in collection [if condition] )
a = (x for x in range(10)) print(a) # <generator object <genexpr> at 0x0000025BE511CC48> print(tuple(a)) # (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
Dictionary Derivation
{ key_expr: value_expr for value in collection [if condition] }
b = {i: i % 2 == 0 for i in range(10) if i % 3 == 0} print(b) # {0: True, 3: False, 6: True, 9: False}
Set derivation
{ expr for value in collection [if condition] }
c = {i for i in [1, 2, 3, 4, 5, 5, 6, 4, 3, 2, 1]} print(c) # {1, 2, 3, 4, 5, 6}