Python-if语句

条件测试
检查是否相等/不相等

car = 'bmw'
print(car == 'bmw')
#True
print(car == 'BMW')
#False
print(car != 'audi')
#Ture

简单的if语句

age = 19
if age >= 18:
    print("You are old enough to votel!")
#You are old enough to votel!

if–else语句

age = 17
if age >= 18:
    print("You are old enough to votel!")
else:
    print("Sorry, you are too young to vote.")
#Sorry, you are too young to vote.
cars = ['audi','bmw','subaru','toyota']
for car in cars:
    if car == 'bmw':
        print(car.upper())
    else:
        print(car.title())
#Audi
#BMW
#Subaru
#Toyota

if–elif-else

age = 12
if age < 4:
    print("Your admission cost is 0$.")
elif age < 18:
    print("Your admission cost is 15$.")
else:
    print("Your admission cost is 10$.")
#Your admission cost is 15$.

if语句对列表的操作

requested_toppings = ['mushroom','green peppers','extra cheese']
for requested_topping in requested_toppings:
    print("Adding " + requested_topping + ".")
print("\nFinished making your pizza!")
#Adding mushroom.
#Adding green peppers.
#Adding extra cheese.

#Finished making your pizza!

确定列表不是空的

requested_toppings = []
if requested_toppings:
    for requested_topping in requested_toppings:
        print("Adding " + requested_topping + ".")
    print("\nFinished making your pizza!")
else:
    print("Are you sure you want a plain pizza?")
#Are you sure you want a plain pizza?

使用多个列表

available_toppings = ['mushroom','olives','green peppers','pepperoni','pineapple','extra cheese']
requested_toppings = ['mushroom','fresh 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.")
#Adding mushroom.
#Sorry, we don't have fresh fries.
#Adding extra cheese.

#Finished making your pizza.
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值