This article mainly introduces the conditional judgment statement in Python, is the basic knowledge in Python introduction, need friends can refer to the
An else statement can be combined using an if statement. If the conditional expression in the If statement resolves to a value of 0 or FALSE, the Else statement contains code execution.
The Else statement is an optional declaration, and there is at most one else statement below the IF statement.
Grammar:
The syntax for the IF ... else statement is:
?
1 2 3 4 |
If Expression:statement (s) else:statement (s) |
Example:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#!/usr/bin/python var1 = + if Var1:print "1-got a true expression value" Print Var1 Else:print "1-got a false ex Pression value "Print var1 var2 = 0 if Var2:print" 2-got a true expression value "Print Var2 else:print" 2-got a F Alse expression value "Print var2 print" Good bye! |
When the above code is executed, the following results are produced:
?
1 2 3 4 5 |
1-got a true expression value 2-got a false expression value 0 good bye! |
Elif statement
The Elif statement can examine the truth of multiple expressions and perform one of the conditions of a code block to evaluate to true.
The IF...ELIF statement is optional. Unlike else, however, you can have up to one statement for this, and an if statement can have any number of elif statements below it.
The syntax for the IF...ELIF statement is:
?
1 2 3 4 5 6 7 8 |
If Expression1:statement (s) elif expression2:statement (s) elif expression3:statement (s) else:statement (s) |
The Python core does not provide switch or case statements in other languages, but we can use the IF. Elif ... Statement to simulate the switch case as follows:
Example
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16-17 |
#!/usr/bin/python var =-if var = 200:print "1-got A true expression value" Print var elif var = 150:print "2- Got a true expression value "Print var elif var = 100:print" 3-got A true expression value "Print var else:print" 4 -Got a false expression value "Print var print" Good bye! " |
When the above code is executed, the following results are produced:
?
|
3-go T a true expression value good bye! |