Python conditional statements are code blocks that are executed based on the execution results (True or False) of one or more statements.
Think about it:
When using if, it can only do what it needs to do when the conditions are met. So what should you do if you need to do something when the conditions are not met?
Answer: else
if 条件: 满足条件时要做的事情1 满足条件时要做的事情2 ...(省略)... else: 不满足条件时要做的事情1 不满足条件时要做的事情2 ...(省略)...
The following uses an example of buying a ticket to help everyone understand.
Result 1: There is a ticket.
chePiao = 1 # 用1代表有车票,0代表没有车票 if chePiao == 1: print("有车票,可以上火车") print("终于可以见到Ta了,美滋滋~~~") else: print("没有车票,不能上车") print("亲爱的,那就下次见了,一票难求啊~~~~(>_<)~~~~")
Run result:
Result 2: Situation without ticket.
chePiao = 0 # 用1代表有车票,0代表没有车票 if chePiao == 1: print("有车票,可以上火车") print("终于可以见到Ta了,美滋滋~~~") else: print("没有车票,不能上车") print("亲爱的,那就下次见了,一票难求啊~~~~(>_<)~~~~")
Result 2: Without ticket, running result:
想一想:
if能完成当xxx时做事情
if-else能完成当xxx时做事情1,否则做事情2
如果有这样一种情况:当xxx1时做事情1,当xxx2时做事情2,当xxx3时做事情3,那该怎么实现呢?
答:elif
if xxx1: 事情1 elif xxx2: 事情2 elif xxx3: 事情3
说明:
- 当xxx1满足时,执行事情1,然后整个if结束。
- 当xxx1不满足时,那么判断xxx2,如果xxx2满足,则执行事情2,然后整个if结束。
- 当xxx1不满足时,xxx2也不满足,如果xxx3满足,则执行事情3,然后整个if结束。
- 当xxx1不满足时,xxx2也不满足,当xxx3不满足时....以此类推,直到整个if结束。
score = 77 if score>=90 and score<=100: print('本次考级,等级为A') elif score>=80 and score<90: print('本次考试,等级为B') elif score>=70 and score<80: print('本次考试,等级为C') elif score>=60 and score<70: print('本次考试,等级为D') elif score>=0 and score<60: print('本次考试,等级为E')
运行结果:
if 性别为男性: 输出男性的特征 ... elif 性别为女性: 输出女性的特征 ... else: 第三种性别的特征 ...
代码说明:
- 当 “性别为男性” 满足时,执行 “输出男性的特征”的相关代码。
- 当 “性别为男性” 不满足时,如果 “性别为女性”满足,则执行 “输出女性的特征”的相关代码。
- 当 “性别为男性” 不满足,“性别为女性”也不满足,那么就默认执行else后面的代码,即 “第三种性别的特征”相关代码。
elif必须和if一起使用,否则出错。
This article is based on the basics of Python and introduces several common conditional judgment statements. Through the actual operation of small projects, we can better understand the conditional judgment statements. usage.
A detailed explanation of the difficulties encountered during the project practice and the points that need attention are given.
The above is the detailed content of Python basic conditional statements. For more information, please follow other related articles on the PHP Chinese website!