python入门_day2_Chap5_if语句

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')

练习

  1. 创建一个包含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)
  1. 序数 :序数表示位置,如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')
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值