if 语句
简单的示例:
cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
if car == "bmw":
print(car.upper())
else:
print(car.title())
1. 使用 使用and 检查多个条件 检查多个条件
要检查是否两个条件都为True ,可使用关键字and 将两个条件测试合而为一;如果每个测试都通过了,整个表达式就为True ;如果至少有一个测试没有通过,整个表达式就 为Fals
2. 使用 使用or 检查多个条件 检查多个条件
关键字or 也能够让你检查多个条件,但只要至少有一个条件满足,就能通过整个测试。仅当两个测试都没有通过时,使用or 的表达式才为False
3.简单的if语句
if conditional_test:
do something
4.if-else 语句
ages = 17
if ages>=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.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.")
if age < 4:
price = 0
elif age < 18:
price = 5
else:
price = 10
print("Your admission cost is $" + str(price) + ".")
requested_toppings = ['mushrooms', 'extra cheese']
if 'mushrooms' in requested_toppings:
print("Adding mushrooms.")
elif 'pepperoni' in requested_toppings:
print("Adding pepperoni.")
elif 'extra cheese' in requested_toppings:
print("Adding extra cheese.")
print("\nFinished making your pizza!")
6.使用多个elif代码块
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) + ".")
7.使用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("Adding" + requested_topping + "")
print("\nFinished making your pizza!")
#确定列表不为空
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?")
#使用多个列表
available_toppings = ['mushrooms', 'olives', 'green peppers', 'pepperoni', 'pineapple', 'extra cheese']
requested_toppings = ['mushrooms', 'french fries', 'extra cheese']
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 + ".")
print("\nFinished making your pizza!")
浙公网安备 33010602011771号