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("\nFinished 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("\nFinished making your pizza")

 

转载于:https://www.cnblogs.com/sunnybowen/p/10163058.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值