python-if语句
程序员文章站
2024-01-05 23:53:10
...
cars = ['audi', 'bmw', 'subaru', 'toyora']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
# 输出结果
# Audi
# BMW
# Subaru
# Toyora
# 检查是否相等
car = 'bmw'
print(car == 'bmw')
# True
# 检查是否相等时不考虑大小写
car = 'Audi'
print(car == 'audi')
print(car.lower() == 'audi') # 将变量的值转换为小写再进行比较
print(car) # lower 函数不会影响变量原来的值
# False
# True
# Audi
# 检查是否不相等
request_topping = "mushrooms"
if request_topping != "anchovies": # 有时候检查两个值是否不相等的效率更高
print("Hold this anchovies!")
# Hold this anchovies!
# 比较数字
age = 18
print(age == 18)
# True
answer = 17
if answer != 43:
print("That is nor correct answer. Please try again")
# That is nor correct answer. Please try again
age = 19
print(age < 21)
# True
# 使用 and 检查多个条件
age_0 = 22
age_1 = 18
print(age_0 >= 22 and age_1 >=21)
age_1 = 22
print(age_0 >= 22 and age_1 >=21)
# False
# True
# 使用 or 检查多个条件
age_0 = 22
age_1 = 18
print(age_0 >= 22 or age_1 >=21)
age_0 = 18
print(age_0 >= 22 or age_1 >=21)
# True
# False
# 检查特定值是否在列表中
# 要判断特定的值是否已经包含在列表中,可使用关键字 in
request_topping = ['mushrooms', 'onions', 'pineapple']
print('mushrooms' in request_topping)
# True
# 检查特定的值是否不包含在列表中
# 确定特定的值未包含在列表中,可以使用关键字 not in
banner_users = ['andrew', 'carolina', 'david']
user = 'maries'
if user not in banner_users:
print(user.title() + ", you can post a response if you wish")
# Maries, you can post a response if you wish
# if 语句
# 简单的 if 语句
age = 19
if age >= 18:
print("you are old enough to vote")
# you are old enough to vote
# if else 语句
age = 17
if age >= 18:
print("you are old enough to vote")
else:
print("sorry you are too young to vote")
# sorry you are too young to vote
# if elif else 语句
age = 12
if age < 4:
print("111")
elif age < 18:
print("222")
else:
print("333")
# 222
# 使用多个 elif 代码块
# 省略 else 代码块
上一篇: MyEclipse编辑的时候光标变成黑块该怎么办?
下一篇: 怎么高效而合理的发布软文呢?