简单的示例:
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) + ".")
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) + ".")
原文:https://www.cnblogs.com/ziweiqi/p/13885367.html