云学编程的第10天—【微软官方python入门教程 P21-P22笔记】2021-11-10 elif和in

这篇博客介绍了Python中如何使用if-elif-else进行条件判断,以及如何通过in操作符检查列表中的元素。通过示例展示了如何优化代码,避免重复的if语句,提高代码的可读性和效率。还提到了如何结合if嵌套来处理更复杂的条件组合,并强调了代码简洁的重要性。

P21 elif和in

 

You may need to check multiple conditions to determine the correct action :(colon)elif

provinve=input('where you are: ')
if provinve.lower() == 'alberta':
    print('tax=0.05')
elif provinve.lower() == 'nunavut':
    print('tax=0.01')
elif provinve.lower() == 'ontario':
    print('tax=0.13')

When you use elif instead of multiple if statements you can add a default action else

provinve=input('where you are: ')
if provinve.lower() == 'alberta':
    print('tax=0.05')
elif provinve.lower() == 'nunavut':
    print('tax=0.01')
elif provinve.lower() == 'ontario':
    print('tax=0.13')
else:
    print('tax=0.15')

 If multiple conditions cause the same action they can be combined into a single condition

provinve=input('where you are: ')
if provinve.lower() == 'alberta'\
    or provinve.lower() == 'nunavut':
    print('tax=0.01')

How OR statements are processed

 If you have a list of possible values to check, you can use the IN operator.

Basically it's for those situations when you find yourself saying if it equals this or it equals this or it equals this or it euqals this or it equals this.....in that case you use something called an 'in'.

provinve=input('where you are: ')
if provinve.lower() in ('alberta','nunavut','yukon'):
    print('tax=0.01')

If an anction depends on a combination of conditions you can nest if statements

country=input('whare are from?')
if country == 'Canada':
    provinve=input('where you are: ')
    if provinve.lower() in ('alberta','nunavut','yukon'):
        print('tax=0.01')
    elif provinve.lower() == 'ontario':
        print('tax=0.13')
    else:
        print('tax=0.15')
else:
    print("I don't understant.")

Four spaces does change how the code is exeuted.

P22实操

province = input('what province do you live in ?')
if province == 'alberta' or province == 'nunavut':
    tax=0.05
elif province == 'ontario':
    tax=0.13
else:
    tax=0.15
print(tax)

always tast every possible condition

leaves one more scenario, i'm going to add a nested if statement:

country = input('what state do you live in ?')
if country.lower() == 'canada':
    province = input('what state do you live in ?')
    if province in('alberta','nunavut','yukon'):
        tax=0.05
    elif province == 'ontario':
        tax=0.13
    else:
        tax=0.15
else:
    tax=0
print(tax)

感想:不重复就是进步

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值