python——if语句

第5章 if语句

本章将学习简单的if语句,以及创建一些复杂的if语句来确定当前到底处于一个什么样的情形。

5.1 一个简单的示例

cars = ['audi', 'bmw', 'subaru', 'toyota']

for car in cars:
    if car == "bmw":
        print(car.upper())
    else:
        print(car.lower())
audi
BMW
subaru
toyota

5.2 条件测试

每条if语句的核心都是一个值为True或False的表达式,这种表达式被称为条件测试。python根据条件测试的值是True还是False来决定是否执行if语句中的代码。
1、检查是否相等。==
2、检查是否不相等。!=
3、检查多个条件。and、or
4、检查特定值是否包含在列表中。in
5、检查特定值是否不包含在列表中。not in

print(cars)
if "audi" in cars:
    print("Audi in this !")
else:
    print("Audi not in this 1")
['audi', 'bmw', 'subaru', 'toyota']
Audi in this !

5.3 if语句

1、最简单的if语句(最简单的if语句只有一个测试和一个操作)
2、if-else语句
3、if-elif-else模块
4、省略else代码块。python并不要求if-elif结构后面必须有else代码块。

age = 25
if age >18 :
    print("You are old enough to vote !")
You are old enough to vote !
if age >= 18:
    print("You are old enough to vote !")
elif age <18:
    print('You are too young to vote !')
You are old enough to vote !

5.4 使用if语句处理列表

通过结合使用if语句和列表,可完成一些任务:
1、检查特殊元素,对其进行操作
2、确定列表不是空的
3、使用多个列表

requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
for request_topping in requested_toppings:
    if request_topping == 'green peppers':
        print("Sorry, we are out of green peppers right now !")
    else:
        print("Adding " + request_topping + ".")
        
Adding mushrooms.
Sorry, we are out of green peppers right now !
Adding extra cheese.
request_toppings = []

if request_toppings:
    for request_topping in request_toppings:
        print("Adding " + request_topping + ".")
else:
    print("Are you sure you want a plain pizza ?")
Are you sure you want a plain pizza ?
available_toppings = ['mushroom', 'olives', 'green peppers', 'extra cheeses']
request_toppings = ['mushroom', 'french fries', 'extra cheeses']
for request_topping in request_toppings:
    if request_topping in available_toppings:
        print("Adding " + request_topping + ".")
    else:
        print("Sorry, we are now out of " + request_topping + ".")
Adding mushroom.
Sorry, we are now out of french fries.
Adding extra cheeses.

练习

1、人生的不同阶段:设置变量age的值,再编写一个if-elif-else结构,根据age的值判断处于人生的哪个阶段。
如果一个人的年龄小于2,指出他是婴儿
如果2-4,指出蹒跚学步
如果4-13,指出他是儿童
如果13-20,指出他是青少年
如果20-65,指出他是成年人
如果年龄超过65,指出他是老年人
2、序数:序数表示位置。如:1st和2nd。大多数序数都是以th结尾,只有1、2、3例外。
在一个列表中存储数字1-9
遍历这个列表。
在循环中使用一个if-elif-else结构以打印每个数字对应的序数,其中每个序数独占一行。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值