In select and loop structures, the value of the conditional expression as long as it is not False, 0 (or 0.0, 0j, etc.), the empty value None, the empty list, the empty tuple, the empty set, the empty dictionary, the empty string, the emptyrange objects or other empty iterable objects are considered equivalent to True by the Python interpreter.
Logical operators and and or and relational operators have lazy evaluation characteristics, Only evaluate expressions that must be evaluated.
Take "and" as an example, for the expression "expression1 and expression2", if the value of "expression1" is "False" or other equivalent values, regardless of the value of "expression2"What is the value, the value of the entire expression is "False", at this time the value of "expression 2" does not affect the value of the entire expression, so it will not be calculated, thereby reducing unnecessary calculations andjudge.
Python also supports expressions of the form:
value1 if condition else value2
When the value of the conditional expression condition is equal to True, the value of the expression is value1, otherwise the value of the expression is value2.Complex expressions, including function calls and basic output statements, can also be used in value1 and value2.Expressions of this structure also feature lazy evaluation.
>> a = 5>>> print(6) if a>3 else print(5)6>>> print(6 if a>3 else 5)6>>> b = 6 if a>13 else 9>>> b9
Lazy Evaluation
#The math module has not been imported at this time>>> x = math. sqrt(9) if 5>3 else random.randint(1, 100)NameError: name 'math' is not defined>>> import math#The random module has not been imported at this time, but since the value of the conditional expression 5>3 is True, it can run normally>>> x = math.sqrt(9) if 5>3 else random.randint(1,100)#The random module has not been imported at this time. Since the value of the conditional expression 2>3 is False, the value of the second expression needs to be calculated, so an error occurs>>> x = math.sqrt(9) if 2>3 else random.randint(1, 100)NameError: name 'random' is not defined>>> import random>>> x = math.sqrt(9) if 2>3 else random.randint(1, 100)
while loop and for loop