if 语句的核心是一个值为 True 或 False 的表达式,Python根据测试值为 True 或 False 来决定是否执行代码
格式 if condition :
do something
stu = 'sd'
print(stu == 'fd')
print(stu != 'fd')
stu = 18
print(stu == 4)
print(stu != 4)
print(stu >= 4)
print(stu <= 4)
print(stu != 4 and stu > 4) # and 逻辑与
print(stu != 4 or stu > 4) # or 逻辑或
stu = {'rew','fey',43,2}
s1 = 'fey'
if s1 in stu: # s1 在 stu 中输出
print("s1 为 ",s1)
s1 = 'fwe'
if s1 not in stu: # s1 不在 stu 中输出
print("s1 为 ",s1)
False
True
False
True
True
False
True
True
s1 为 fey
s1 为 fwe
格式(1) if condition: (2) if condition:
do something do something
else: elif condition:
do something do something
else:
do something
stu = {'rew','fey',43,2}
s1 = 'fey'
if s1 in stu: # s1 在 stu 中输出
print("s1 在 stu")
else: # s1 不在 stu 中输出
print("s1 不在 stu")
s1 = 5
if s1 not in stu:
print("s1 不在 stu")
elif s1 in stu:
print("s1 在 stu")
else:
print("其他")
s1 在 stu
s1 不在 stu
fruit = {'apple','banana','orange','pear'}
foods = {'rice','beef','pork','pear'}
for val in foods:
if val in fruit:
print(val.title())
else:
print("foods not fruit")
foods not fruit
foods not fruit
foods not fruit
Pear