Chap5 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多条件判断语句
使用 and or
if num>1 and num<100
检验特定值是否在列表中
foods=['duck','carrot','apple']
meat='duck'
if meat in foods:
print("Yes")
if meat not in foods:
print("No")
布尔表达式
bool类型变量的值 为 True或者False
5.3 if 语句
if-elif-else语句
例如,来看一个根据年龄段收费的游乐场:
4岁以下免费;
4~18岁收费5美元;
18岁(含)以上收费10美元。
age=int(input('请输入您的年龄'))
if age<4:
print('your ticket cost is $0')
elif age<18 and age>4:
print('your ticket cost is $5')
else:
print('you ticker cost is $10')
5.4使用if语句处理列表
简单例子
foods=['apple','cherry','pear','banana']
for food in foods:
if food=='cherry':
print('Sorry,there is no more cherry')
else:
print(food+' is ready to serve')
print('enjoy your foods')
使用多个列表
foods=['apple','cherry','pear','banana','duck','chicken','popcorn']
available_foods=['apple','cherry','pear','banana']
short_foods=['duck','chicken','popcorn']
for food in foods:
if food in short_foods:
print('Sorry,there is no more cherry')
elif food in available_foods:
print(food+' is ready to serve')
print('enjoy your foods')
练习
- 创建一个包含5个用户名的列表,并将其命名为current_users 。
再创建一个包含5个用户名的列表,将其命名为new_users 。
遍历列表new_users ,都检查每个用户名是否使用。
确保比较时不区分大小写
current_users=['Tom','Jerry','Ian','Fiona','Carl']
new_users=['Lip','Jimmy','Vin','Liam','Ingird','Carl','TOM']
lower_users=[]
for current_user in current_users:
lower_users.append(current_user.lower())
for new_user in new_users:
if new_user.lower() in lower_users:
print(new_user+' is already taken')
else:
print('hello, '+new_user)
- 序数 :序数表示位置,如1st和2nd。大多数序数都以th结尾,只有1、2和3例外。 在一个列表中存储数字1~9。遍历这个列表。
在循环中使用一个if-elif-else 结构,以打印每个数字的序数。
输出内容应为1st 、2nd 、3rd 、4th 、5th 、6th 、7th 、8th 和9th ,但每个序 数都独占一行。
nums=list(range(1,10))
print(nums)
for num in nums:
if num==1:
print(str(num)+'st')
elif num==2:
print(str(num)+'nd')
elif num==3:
print(str(num)+'rd')
else:
print(str(num)+'st')