学习笔记 | 2021-1-10

第5章 if语句

5.1 一个简单示例

cars.py

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

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

5.2 条件测试

  1. 检查是否相等;
  2. 检查是否相等时不考虑大小写;
    例如,两个大小写不同的值会被视为不相等。
car = 'Audi'
car == 'audi'
False
  1. 检查是否不相等;
  2. 比较数字;
  3. 检查多个条件:
    (1)使用and检查多个条件;
    (2)使用or检查多个条件;
  4. 检查特定值是否包含在列表中:
 requested_toppings = ['mushrooms', 'onions', 'pineapple']
 'mushrooms' in requested_toppings 
 Ture
 'pepperoni' in requested_toppings
 False
  1. 检查特定值是否不包含在列表中:
 banned_users.py

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

if user not in banned_users:
	print(user.title() + ", you can post a response if you wish.")
  1. 布尔表达式:
game_active = True
can_edit = False

5.3 if语句

  1. 简单的if语句:
if conditional_test:
	do something
  1. if-else语句;

  2. if-elif-else结构;

  3. 使用多个elif代码块;

  4. 省略else代码块:
    经过这样的修改后,每个代码块都仅在通过了相应的测试时才会执行。
    else是一条包罗万象的语句,只要不满足任何if或elif中的条件测试,其中的代码就会执行,这可能会引入无效甚至恶意的数据。如果知道最终要测试的条件,应考虑使用一个elif代码来代替else代码块。这样,你就可以肯定,仅当满足相应的条件时,你的代码才会执行。

  5. 测试多个条件:
    有时候必须检查你关心的所有条件:

toppings.py

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!")

如果转而使用if-elif-else结构,代码将不能正确地运行,因为有一个测试通过后,就会跳过余下的测试。
总之,如果你只想执行一个代码块,就使用if-elif-else结构;如果要运行多个代码块,就使用一系列独立的if语句。

5.4 使用if语句处理列表

  1. 检查特殊元素;
  2. 确定列表不是空的;
  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("Adding " + requested_topping + ".")
	else:
		print("Sorry, we don't have " + requested_topping + ".")

print("\nFinished making your pizza!")

5.5 设置if语句的格式

在条件测试的格式设置方面,PEP 8提供的唯一建议是,在诸如==、>=和<=等比较运算符两边各添加一个空格。这样的空格不会影响Python对代码的解读,而只是让代码阅读起来更容易。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值