栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

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

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

云学编程的第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)

感想:不重复就是进步

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/461484.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号