Python编程从入门到实践-学习笔记之三(if语句)

第5章 if语句

检查是否相等:==

区分大小写,如果不需要区分,可将变量转换为小写后再比较。

检查是否不相等:!=

比较数字

检查多个条件:and/or

可将每个检查条件放在()内,改善可读性

检查特定值是否包含(不包含)在列表中:in(not in)

cars.py

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

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

cars[0] = 'Audi'

print(cars)

if cars[0].lower() == 'audi':
	print('True')

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

布尔表达式

if

if-else

if-elif-else

amusement_park.py

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) + ".")

不使用 else,而用elif age>=65逻辑更清晰

if-elif-else仅适合用于只有一个条件满足的情况,在可能有多个条件为True时,应当使用多个简单if语句。

使用if语句处理列表

检查特殊元素

确定列表不是空的

使用多个列表

toppings.py

requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
if 'mushrooms' in requested_toppings:
	print("Adding mushrooms.")
if 'pepperoni' in requested_toppings:
	print("Adding peperoni.")
if 'extra cheese' in requested_toppings:
	print("Adding extra cheese.")
	
print("\nFinished making your pizza!")

requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
for requested_topping in requested_toppings:
	print("Adding " + requested_topping + ".") 
print("\nFinished 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("Adding " + requested_topping + ".") 
print("\nFinished 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?")
	
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!")

2023年9月14日

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

逆旅匆匆

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值