Python Day 4 2020-4-9
Python if语句
条件测试
1.检查是否相等
大多数条件测试都将一个变量的当前值同特定值进行比较。
>>> car = 'bmw'
>>> car == 'bmw'
2.检查是否相等时不考虑大小写
在Python中检查是否相等时区分大小写`
>>> car = 'Audi'
>>> car.lower() == 'audi'
True
3.检查是否不相等
要判断两个值是否不等,可结合使用惊叹号和等号(!=)
4.比较数字
条件语句中可包含各种数学比较,如小于、小于等于、大于、大于等于等
>>> age = 18
>>> age == 18
True
5.检查多个条件
(1)使用and检查多个条件
(2)使用or检查多个条件
6.检查特定值是否包含在列表中
要判断特定的值是否已包含在列表中,可使用关键字in。
>>> requested_toppings = ['mushrooms', 'onions', 'pineapple']
>>> 'mushrooms' in requested_toppings
True
7.检查特定值是否不包含在列表中
要判断特定的值是否未包含在列表中,可使用关键字not in。
banned_users = ['andrew', 'carolina', 'david']
user = 'marie'
if user not in banned_users:
print(user.title() + ", you can post a response if you wish.")
8.布尔表达式
if语句
1.简单的 if 语句
最简单的if语句只有一个测试和一个操作
age = 19
if age >= 18:
print("You are old enough to vote!")
2.if-else 语句
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!")
3.if-elif-else 结构
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.")
3.使用多个 elif 代码块
4.省略 else 代码块
Python并不要求if-elif结构后面必须有else代码块。在有些情况下,else代码块很有用;而在其他一些情况下,使用一条elif语句来处理特定的情形更清晰。
5.测试多个条件
使用 if 语句处理列表
1.检查特殊元素
可在for循环中包含一条if语句
requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
for requested_topping in requested_toppings:
if requested_topping == 'green peppers':
print("Sorry, we are out of green peppers right now.")
else:
print