python ch5 if语句

# 如何编写简单的if语句、if-else语句和if-elif-else结构。在程序中,你使用了这些结构来测试特定的条
#  件,以确定这些条件是否满足。你学习了如何在利用高效的for循环的同时,以不同于其他元素
#  的方式对特定的列表元素进行处理。你还再次学习了Python就代码格式方面提出的建议,这可确
#  保即便你编写的程序越来越复杂,其代码依然易于阅读和理解。
# if
cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
    if car == 'bmw':
        print(car.upper())
    else:
        print(car.title())

    #检测是否相等
    print(car == 'bmw')

# 使用and检查多个条件
age_0 = 22
age_1 = 18
print("")
print(age_0 >=21 and age_1 >=21)
print(age_0 >=21 or age_1 >=21)

# 要判断特定的值是否已包含在列表中,可使用关键字in
requested_toppings = ['mushrooms', 'onions', 'pineapple']
print()
print( 'mushrooms' in requested_toppings)
print( 'mushroom' in requested_toppings)

# if else
age = 17
if age >= 18:
    print("You are old enough to vote!")
    print("Have you registered to vote yet?")
else:
    print("Sorry, you are too young to vote.")
    print("Please register to vote as soon as you turn 18!")

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

# 使用多个 elif 代码块
print()
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) + ".")

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值