5200.4 IF Statements

if 声明是一个表达式,可以根据 true 和 false 执行不同的代码块。

条件测试

  • ==
  • !=
  • =

  • <

多条件测试

  • and
  • or

关于 List 的判断

是否在List

用关键词in

requested_toppings = ['mushrooms', 'onions', 'pineapple']
print('mushrooms' in requested_toppings)

是否不在List 中

用关键词not in

if user not in banned_users:
	print(f"{user.title()}, you can post a response if you wish.")

If 块

  • if
  • elif
  • else

elif 可以多次使用 省略 else 的关键词,就让你对判断语句更有掌控感,else 是一个兜底方案。

Note

如果需要多个条件都执行,而不是被 elif 或 else 跳过的话,就全部使用 if 语句。

# 全部 if
requested_toppings = ['mushrooms', 'extra cheese'] 
if 'mushrooms' in requested_toppings:
	print("Adding mushrooms.")
if 'pepperoni' in requested_toppings:
	print("Adding pepperoni.")
if 'extra cheese' in requested_toppings:
	print("Adding extra cheese.")
print("\nFinished making your pizza!")