- Q:条件测试
- A:
- 检查是否相等 ==
- 检查是否不等 !=
- 检查多个条件 and or
- 检查特定值是否包含在列表中 关键字 in
- 检查特定值是否不包含在列表中 关键字 not in
# 下面是检查是否相等的条件测试
>>>car = 'bmw'
>>>car == 'bmw'
>>>true
对于python来说检查是否相等大小写是考虑的
# 下面是检查是否不等的条件测试
requested_topping = 'mushromms'
if requested_topping != 'anchovies':
print("Hold the anchovies!")
# 下面是检查多个条件
>>>age_0 = 22
>>>age_1 = 18
>>>age_0 >= 21 and age_1 >= 21
False
>>>age_1 = 20
>>>age_0 >= 21 or age_1 >= 21
True
# and需要条件都通过才会返回True
# or 只要一个条件通过就返回True
# 下面是特定值是否包含在列表中
>>>requested_topping = ['mushrooms','onions','pineapple"]
>>>'mushrooms' in requested_topings
True
>>>"pepperoni" in requested_toppings
False
# 下面是检查特定值是否不包含在列表中
banned_ users = ['andrew','carolina','david']
user = 'marie'
if user not in banned_ users:
print(user.title() + ", you can post a response if you wish.")
# 每条if语句的核心都是一个值为True或False的表达式,这种表达式被称为条件测试。Python根据条件测试的值为True还是False来决定是否执行if语句中的代码。如果条件测试的值为True,Python就执行紧跟在if语句后面的代码;如果为False, Python就忽略这 些代码。
- Q:if-else 语句
- A:测试条件中未通过部分的方法
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!")
------------------------------------------------------------------
Sorry, you are too young to vote.
Please register to vote as soon as you turn 18!
# if-else结构适合要让python执行两种操作之一的情形
- Q:if-elif-else 结构
- A:测试条件中别的情形的方法
# 下面是一个根据年龄收费的游乐场
·4岁以下免费;
·4~ 18岁收费5美元;
·18岁(含)以上收费10美元。
age = 12
ifage < 4:
print("Your admission cost is $0.")
elif age < 18:
print("Your admission cost is $5.")
else:
print("Your admission cost is $10.")
------------------------------------------------------------------
Your admission cost is $5.
# 上面的代码也可以简化下 只在最后打印prices即可
age = 12
ifage<4:
price = 0
elif age < 18:
price = 5
else:
price = 10
print("Your admission cost is $" + str(price) + ".")
# 也可以使用多个elif代码块
age = 12
ifage<4:
price = 0
elif age < 18:
price = 5
elif age < 65:
price = 10
else:
price = 5
print("Your admission cost is $" + str(price) + ".")
# 上面的代码我们也可以省略else代码来使条件更清晰
age = 12
if age < 4:
price = 0
elif age < 18:
price。5
elif age < 65:
price。10
elif age >= 65:
price = 5
print("Your admission cost is $" + str(price) + ".")
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("
Finished making your pizza!")
------------------------------------------------------------------
Adding mushrooms.
Adding extra cheese.
Finished making your pizzal!