1、if...else...语句
cars=['audi','bmw','subaru','toyota']
for car in cars:
if car=='bmw': #if...else...
print(car.upper())#如果满足条件,则执行该语句,执行完后跳出if,不再执行else
else:
print(car.title())#如果不满足,执行该语句
2、if...elif...else语句
cars=['audi','bmw','subaru','toyota']
for car in cars:
if car=='bmw': #if...else...
print(car.upper())#如果满足条件,则执行该语句
elif car=='subaru':#如果满足elif条件,则执行该语句
print(car.upper())
else:
print(car.title())#如果不满足,执行该语句
3、if...elif..elif...else语句
cars=['audi','bmw','subaru','toyota']
for car in cars:
if car=='bmw': #if...else...
print(car.upper())#如果满足条件,则执行该语句,执行完后跳出if,不再执行else
elif car=='subaru':#如果满足elif条件,则执行该语句,
print(car.upper())
elif car=='toyota':
print(car.upper())#如果满足elif条件,则执行该语句,
else:
print(car.title())#如果不满足,执行该语句,有时可去除else部分
以上条件中可用到or 、and 及in
cars=['audi','bmw','subaru','toyota'] request_cars=['beek','bmw','audi'] for car in cars:#从cars列表中取出一个值 if car in request_cars:#如果request——cars中有car,则执行该语句 print('有'+car+'.')