Python编程从入门到实践_第五章_if语句

第五章_if语句


5.1 一个简单的示例

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

for car in cars:
    if car =='bmw':
        print(car.upper())
    else:
        print(car.title())
        
Audi
BMW
Subaru
Toyota

5.2 条件测试

  • 每条if语句的核心是一个值为True 或 False 的表达式,该表达式称为条件测试
  • Python 根据条件测试的值为True 或 False来决定是否执行if中的代码

5.2.1 检查条件是否相等——==

car = 'bmw'
car == 'bmw'
True

注意:

  • 一个等号 “=”:赋值
  • 两个等号“==”:判断

5.2.2 检查是否相等时忽略大小写

  • Python 检查是否相等时区分大小写
car = 'Audi'
car == 'audi'
False
car = 'Audi'
car.lower() == 'audi'
True

5.2.3 检查是否不相等——!=

  • 有些情况下检查两个值不相等的效率更高
request_topping = 'mushrooms'

if request_topping != 'anchovies':
    print("Hold the anchovies!")
 Hold the anchovies!

5.2.4 数值比较

  • 常用数值比较操作:==,!=,>,<,>=,<=
answer = 17

if answer != 42:
    print("That is not the correct answer. Please try again!")
That is not the correct answer. Please try again!

5.2.5 检查多个条件

  • and: 每个条件都满足,True;至少一个条件不满足,False
  • or: 至少有一个条件满足,True;所有条件均不满足,False
age_0 = 22
age_1 = 18
age_0 >= 21 and age_1 >= 21
False

5.2.6 检查特定值是否包含在列表中—— in

request_toppings = ['mushrooms', 'onions','pineapple']

'mushrooms' in request_toppings
True
request_toppings = ['mushrooms', 'onions','pineapple']

'pepperoni' in request_toppings
False

5.2.7 检查特定值是否不包含在列表中—— not in

banned_uses = ['andrew','carolina','david']
user = 'marie'

if user not in banned_uses:
    print(f"{user.title()}, you can post a reponse if you wish.")
Marie, you can post a reponse if you wish.

5.2.8 布尔表达式

  • 布尔表达式(Boolean expression)是一段代码声明,它最终只有true(真)和false(假)两个取值。
  • 从最基本的层次来说,所有的布尔表达式,不论它的长短如何,其值只能是true或false。
game_active = True
can_edit = False

5.3 if 语句

5.3.1 简单的if语句

  • 只包含一个测试和一个操作
age = 19
if age >= 18:
    print("You are old enough to vote!")
You are old enough to vote!
age = 19
if age >= 18:
    print("You are old enough to vote!")
    print("Have you registered to vote yet?")
You are old enough to vote!
Have you registered to vote yet?

5.3.2 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!")
Sorry, you are too young to vote.
Please register to vote as soon as you turn 18!

5.3.3 if-elif-else结构

注意:

- 可以使用多个elif代码块
- Python并不要求if-elif结构后必须有else代码块
- else 可能会引入无效甚至恶意的数据。如果知道最终要测试的条件,应考虑用elif代码块来替代else代码块
age = 12

if age < 4:
    price = 0
elif age < 18:
    price = 25
elif age < 65:
    price = 40
else:
    price = 20

print(f"Your admission cost is ${price}.")
Your admission cost is $25.
age = 12

if age < 4:
    price = 0
elif age < 18:
    price = 25
elif age < 65:
    price = 40
elif age >=65:
    price = 20

print(f"Your admission cost is ${price}.")

Your admission cost is $25.

5.3.6 测试多个条件

  • if-elif-else 结构功能强大,但仅适用于只有一个条件满足的情况,遇到通过了的测试后,python就会跳过其余的测试
  • 要检测多个条件,应使用一系列不包含elif和else的简单if语句
  • 只想执行一个代码块,使用 if-elif-else 结构;要执行多个代码块,使用一系列独立的if语句
requested_toppings = ['mushrooms', 'extra cheese']

if 'mushrooms' in requested_toppings:
        print("Adding mushrooms.")
if 'pepperoni' in requested_toppings:
        print("Adding pepperoni.")
if 'extra cheese' in requested_toppings:
        print("Adding extra cheese.")        
             
print("\nFinished making your pizza!")
Adding mushrooms.
Adding extra cheese.

Finished making your pizza!
requested_toppings = ['mushrooms', 'extra cheese']

if 'mushrooms' in requested_toppings:
        print("Adding mushrooms.")
elif 'pepperoni' in requested_toppings:
        print("Adding pepperoni.")
elif 'extra cheese' in requested_toppings:
        print("Adding extra cheese.")        
             
print("\nFinished making your pizza!")
Adding mushrooms.

Finished making your pizza!
print([value ** 2 for value in range(1,11)])
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

5.4 使用if语句处理列表

5.4.1 检查特殊元素

requested_toppings = ['mushrooms','green peppers', 'extra cheese']

for requested_topping in requested_toppings:
    print(f"Adding {requested_topping}.")
    
print("\nFinished making your pizza!")
Adding mushrooms.
Adding green peppers.
Adding extra cheese.

Finished making your pizza!

requested_toppings = ['mushrooms','green peppers', 'extra cheese']

for requested_topping in requested_toppings:
    if requested_topping == "green peppers":
        print("Sorry, we are out of green peppers right now.")
    else:
        print(f"Adding {requested_topping}.")
    
print("\nFinished making your pizza!")

Adding mushrooms.
Sorry, we are out of green peppers right now.
Adding extra cheese.

Finished making your pizza!

5.4.2 确定列表不为空

任务:制作披萨前检查顾客点的配料列表是否为空,如果列表为空,向顾客确认是否要点原味披萨;如果不为空,按照前面示例制作披萨。

requested_toppings = []

if requested_toppings:
    for requested_topping in requested_toppings:
        print(f"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?

5.4.3 使用多个列表

任务:如何拒绝奇怪的配料要求。

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(f"Adding {requested_topping}.")
    else:
        print(f"Sorry, we don't have {requested_topping}.")
        
print("\nFinished making your pizza!")
Adding mushrooms.
Sorry, we don't have french fries.
Adding extra cheese.

Finished making your pizza!

5.5 设置if语句的格式

  • 在比较运算符两边各添一个空格,便于代码阅读。
if age <= 4:
if age<=4:

总结

在这里插入图片描述

练习

  1. 以特殊方式跟管理员打招呼

    • 创建一个至少包含 5 个用户名的列表,且其中一个用户名为 ‘admin’ 。想象你要编写代码,在每位用户登录网站后都打印一条问候消息。遍历用户名列表,并向每位用户打印一条问候消息:
    • 如果用户名为 ‘admin’ ,就打印一条特殊的问候消息,如 Hello admin, would you like to see a status report?。
    • 否则,打印一条普通的问候消息,如 Hello Eric, thank you for logging in again。
  2. 处理没有用户的情形

    • 在为完成练习 5-8 编写的程序中,添加一条 if 语句,检查用户名列表是否为空。
    • 如果为空,就打印消息 We need to find some users!。
    • 删除列表中的所有用户名, 确定将打印正确的消息。
  3. 检查用户名

    • 按下面说的编写一个程序,模拟网站确保每位用户的用户名都独一无二的方式。
    • 创建一个至少包含 5 个用户名的列表,并将其命名为 current_users 。
    • 再创建一个包含 5 个用户名的列表,将其命名为 new_users ,并确保其中有一两个用户名也包含在列表 current_users 中。
    • 遍历列表 new_users ,对于其中的每个用户名,都检查它是否已被使用。如果是这样,就打印一条消息,指出需要输入别的用户名;否则,打印一条消息,指出这个用户名未被使用。
    • 确保比较是不区分大消息;换句话说,如果用户名 ‘John’ 已被使用,应拒绝用户名’JOHN’ 。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值