#if-else语句格式,比如:
cars=['bmw','audi','toyota','subaru']
for car in cars:
if car=='bmw':
print(car.upper())
else:
print(car.title())
#if-else-if语句格式,比如:
age=66
if age<2:
print("婴儿!")
elif age<4:
print("蹒跚学步!")
elif age<13:
print("儿童!")
elif age<20:
print("青少年!")
elif age<65:
print("成年人!")
else:
print("老年人!")
#使用if检查特殊元素,比如:
requested_toppings=['mushroom','green peppers','extra cheese']
for requested_topping in requested_toppings:
if requested_topping=='green peppers':
print("Sorry,we are out of "+requested_topping+" right now.")
else:
print("Adding "+requested_topping+".")
#使用if确定列表不是空的,比如:
accounts=[]
if accounts:
for account in accounts:
print("Hello " + account + ",thank you for logging in again.")
else:
print("We need to find some users!")
#使用if多个列表,比如:
available_toopings=['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_toopings:
print("Adding "+requested_topping+".")
else:
print("Sorry,we dont't have "+requested_topping+".")
本文详细介绍了Python中if-else及if-elif-else语句的使用方法,包括如何检查列表元素、确保列表非空以及比较多个列表。通过具体代码示例,读者可以深入理解这些语句在实际编程中的应用。
3825

被折叠的 条评论
为什么被折叠?



