Python---if语句

本文深入探讨Python中的条件语句使用,包括if、elif、else的结构,以及如何使用and、or进行复合条件判断。同时,讲解了如何在Python中操作列表,包括检查列表是否包含特定值、确定列表是否为空以及使用多个列表进行复杂操作。

# 参考《Python编程:从入门到实践》进行学习

# 有C或C++基础

# 大多代码运行结果不给出,可copy

示例:

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

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

对于"bmw"进行全大写打印,其余首字母大写打印。

 

检查多个条件

1. and

age = 20
print(age>18 and age<22)

2. or

age = 20
print(age>22 or age<22)

 

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

用关键词in

requested_toppings = ['mushrooms','onions','pineapple']
print('mushrooms' in requested_toppings)
print('pepperoni' in requested_toppings)

 

检查特定值是否不包含在列表中

用关键词not in

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-elif-else结构

age = 12
if age < 4:
	price=0
elif age < 18:
	price=5
else:
	price=10
print("Your admission cost is $"+str(price)+'.')

可使用多个elif代码块。

可省略else代码块。

 

检查特殊元素

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!")
current_users = ['Mike','admin','Eric','Jack','Bay']
new_users = ['Mary','Mike','John','Bay','Yahoo']
for new_user in new_users:
	if new_user in current_users:
		print("Please input other user name:")
	else:
		print("This name can be used.")

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值