Python conditional statements are code blocks that are executed based on the execution results (True or False) of one or more statements.
You can simply understand the execution process of conditional statements through the following figure:
The Python programming language specifies that any non-0 and non-null value is true, and 0 or null is false.程Python programming IF statement is used to control the execution of the program. The basic form is:
IF judgment conditions:
execute statement ...
Lse:
execute statement ...
🎜🎜 🎜🎜🎜🎜 🎜🎜🎜🎜 When the "judgment condition" is true (non-zero), the following statements will be executed, and the execution content can be multiple lines, and the same range is represented by indentation. 🎜🎜else is an optional statement. When you need to execute content when the condition is not true, you can execute related statements. The specific examples are as follows: 🎜🎜🎜🎜🎜🎜# Example 1: Basic usage of if 🎜
# coding = gb2312
flag = False
name = 'luren'
if name == 'python': # 判断变量否为'python'
flag = True # 条件成立时设置标志为真
print 'welcome boss' # 并输出欢迎信息
else:
print name # 条件不成立时输出变量名称
>>> luren # 输出结果
Copy after login
🎜 🎜🎜🎜🎜if statement judgment Conditions can use > (greater than), < (less than), == (equal to), >= (greater than or equal to), <= (less than or equal to) to express their relationships. 🎜🎜When the judgment condition has multiple values, you can use the following form: 🎜🎜🎜🎜🎜🎜if Judgment condition 1:🎜🎜 Execute statement 1...🎜🎜elif Judgment condition 2:🎜🎜 Execute statement 2...🎜🎜 elif Judgment condition 3:🎜🎜 Execution statement 3...🎜🎜else:🎜🎜 Execution statement 4...🎜🎜 🎜🎜🎜🎜The example is as follows: 🎜🎜🎜
# 例2:elif用法
num = 5
if num == 3: # 判断num的值
print 'boss'
elif num == 2:
print 'user'
elif num == 1:
print 'worker'
elif num < 0: # 值小于零时输出
print 'error'
else:
print 'roadman' # 条件均不成立时输出
>>> roadman # 输出结果
Copy after login
🎜 Since python does not The switch statement is supported, so Multiple conditional judgments can only be implemented using elif. If the judgment requires multiple conditions and need 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 true; when using and (and), it means The judgment condition is successful only if both conditions are true at the same time. 🎜🎜🎜🎜🎜🎜# Example 3: Multiple conditions in if statement 🎜
num = 9
if num >= 0 and num <= 10: # 判断值是否在0~10之间
print 'hello'
>>> hello # 输出结果
num = 10
if num < 0 or num > 10: # 判断值是否在小于0或大于10
print 'hello'
else:
print 'undefine'
>>> undefine # 输出结果
num = 8
# 判断值是否在0~5或者10~15之间
if (num >= 0 and num <= 5) or (num >= 10 and num <=15):
print 'hello'
else:
print 'undefine'
>>> undefine # 输出结果
Copy after login
🎜 🎜🎜🎜🎜 When if has multiple conditions, brackets can be used to distinguish the order of judgments. The judgments in brackets are executed first. In addition, and and or The priority of is lower than that of > (greater than),