This article mainly introduces the condition judgment statement in Python, which is the basic knowledge in getting started with Python. you can refer to the next else statement to combine the if statement. If the conditional expression in the if statement is parsed to 0 or false, the else statement contains code execution.
The else statement is an optional statement, and there is only one else statement under the if statement.
Syntax:
The syntax of the if... else statement is:
if expression: statement(s)else: statement(s)
Example:
#!/usr/bin/pythonvar1 = 100if var1: print "1 - Got a true expression value" print var1else: print "1 - Got a false expression value" print var1var2 = 0if var2: print "2 - Got a true expression value" print var2else: print "2 - Got a false expression value" print var2print "Good bye!"
When the above code is executed, the following results are generated:
1 - Got a true expression value1002 - Got a false expression value0Good bye!
Elif statement
The elif statement can check the true values of multiple expressions and execute one of the conditions in a code block to calculate the result as true.
The if... elif statement is optional. However, unlike else, you can have up to one statement. if statements can have any number of elif statements.
The syntax of the if... elif statement is:
if expression1: statement(s)elif expression2: statement(s)elif expression3: statement(s)else: statement(s)
The Python core does not provide the switch or case statement in other languages, but we can use the if... elif... statement to simulate the switch case as follows:
Example
#!/usr/bin/pythonvar = 100if var == 200: print "1 - Got a true expression value" print varelif var == 150: print "2 - Got a true expression value" print varelif var == 100: print "3 - Got a true expression value" print varelse: print "4 - Got a false expression value" print varprint "Good bye!"
When the above code is executed, the following results are generated:
3 - Got a true expression value100Good bye!