条件判断
1. 条件语句
1.1 if格式
if <条件判断1>:
<执行1>
elif <条件判断2>:
<执行2>
elif <条件判断3>:
<执行3>
else:
<执行4>
以上是if语句的完整格式,注意事项:
- Python使用缩进规则,如果if判断条件为true,则执行缩进部分的内容。
- if的执行逻辑是从上往下判断,如果某个判断为true,则会忽略剩下的
elif和else。
例如:以下例子打印的结果是teenager,即满足第一个if条件则后续判断不再执行。
age = 20
if age >= 6:
print('teenager')
elif age >= 18:
print('adult')
else:
print('kid')
1.2 条件简写
if x:
print('True')
只要x是非零数值、非空字符串、非空list等,就判断为True,否则为False。
1.3 input()使用
s = input('birth: ')
birth = int(s)
if birth < 2000:
print('00前')
else:
print('00后')
input()返回的数据类型是str,str不能直接和整数比较,必须先把str转换成整数。Python提供了int()函数来转换成整数。
参考:
Feedback
Was this page helpful?
Glad to hear it! Please tell us how we can improve.
Sorry to hear that. Please tell us how we can improve.
最后修改 October 27, 2025: add python-notes (a78b61d)