banned_users = ['andrew', 'carolina', 'david'] user = 'marie'
if user notin banned_users: print(user.title() + ", you can post a response if you wish.")
Marie, you can post a response if you wish.
5.2.8 布尔表达式
与条件表达式一样,布尔表达式的结果要么为 True,要么为 False。
1 2
game_active = True can_edit = False
5.3 if 语句
if 语句有很多种,选择使用哪种取决于要测试的条件数。
5.3.1 简单的 if 语句
是否到了18岁,他能投票吗
1 2 3
age = 19 if age >= 18: print("You are old enough to vote!")
if 语句中,如果测试通过了,将执行 if 语句后面所有缩进的代码,否则忽略他们。
1 2 3 4
age = 19 if age >= 18: print("You are old enough to vote!") print("Have you registered to vote yet?")
5.3.2 if-else 语句
1 2 3 4 5 6 7
age = 17 if age >= 18: print("You are old enough to vote!") print("Have you registered to vote yet?") else: print("Sorry, you are too young to vote.") print("Please register to vote as soon as you turn 18!")
5.3.3 if-elif-else 结构
1 2 3 4 5 6 7 8
age = 12
if age < 4: print("Your admission cost is $0.") elif age < 18: print("Your admission cost is $5.") else: print("Your admission cost is $10.")
5.3.4 使用多个elif 代码块
1 2 3 4 5 6 7 8 9 10 11 12
age = 12
if age < 4: price = 0 elif age < 18: price = 5 elif age < 65: price = 10 else: price = 5
print("Your admission cost is $" + str(price) + ".")
for requested_topping in requested_toppings: if requested_topping == 'green peppers': print("Sorry, we are out of green peppers right now.") else: print("Adding " + requested_topping + ".")
print("\nFinished making your pizza!")
5.4.2 确定列表不是空的
在 if 语句中将列表名用在条件表达式中时, Python 将在列表中至少包含一个元素时返回 True,当列表 为空时返回 False。
1 2 3 4 5 6 7 8
requested_toppings = []
if requested_toppings: for requested_topping in requested_toppings: print("Adding " + requested_topping + ".") print("\nFinished making your pizza!") else: print("Are you sure you want a plain pizza?")
5.4.3 使用多个列表
1 2 3 4 5 6 7
for requested_topping in requested_toppings: if requested_topping in available_toppings: print("Adding " + requested_topping + ".") else: print("Sorry, we don't have " + requested_topping + ".")