作者:金和裤城_996 | 来源:互联网 | 2023-10-10 09:04
篇首语:本文由编程笔记#小编为大家整理,主要介绍了Python(13)_if语句相关的知识,希望对你有一定的参考价值。
# if 语句与for循环语句,这个模式在实际编程中经常用
cars = [‘audi‘,‘bmw‘,‘subaru‘,‘toyota‘]
for car in cars:
if car == ‘bmw‘:
print(car.upper())
else:
print(car.title())
程序2 :if语句
# if语句
age =7;
if age>=18:
print("You are old enough to vote!")
# if与else
if age>=18:
print("You are old enough to vote!")
else:
print("Sorry,you are too young to vote.")
程序3 :使用多个elif代码块
# 使用多个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)+".")
程序:4:省略else代码块
‘‘‘else 是一条包罗万象的语句,只要不满足任何if 或elif 中的条件测试,其中的代码就会执行,这可能会引入无效甚至恶意的数据。如果知道最终要测试的条件,应考虑使用
一个elif 代码块来代替else 仅当满足相应的条件时,你的代码才会执行。‘‘‘
# 省略else代码块
age = 98
if age<4:
price = 0
elif age<18:
price = 5
elif age<65:
price=10
elif age>=65:
price =5
print("Your admission cost is $"+str(price)+".")
程序6:if语句下嵌套for循环
‘‘‘在这里,我们首先创建了一个空列表,其中不包含任何配料。在处我们进行了简单检查,而不是直接执行for 循环。在if 语句中将列表名用在条件表达式中
时,Python将在列表至少包含一个元素时返回True ,并在列表为空时返回False 。如果requested_toppings 不为空,就运行与前一个示例相同的for 循环;否则,就打印
一条消息,询问顾客是否确实要点不加任何配料的普通比萨‘‘‘
requests =[]
if requests:
for request in requests:
print("Adding "+request+".")
print("
Finished making your pizza")
else:
print("Are you sure you want a plain pizza")
程序7:多个列表,这种形式的在实际编码中也常见
# 多个列表,这种形式的在实际编码中也常见
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("
Finished making your pizza")