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

被折叠的 条评论
为什么被折叠?



