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

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

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

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)

感想:不重复就是进步

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5436989.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-11
下一篇 2022-12-11

发表评论

登录后才能评论

评论列表(0条)

保存