Python学习之条件控制
条件语句是通过一条或多条语句的执行结果(True 或者 False)来决定执行的代码块。
if语句
一般形式如下:
if condition_1: statement_block_1 elif condition_2: statement_block_2 else: statement_block_3
- 如果 "condition_1" 为 True 将执行 "statement_block_1" 块语句
- 如果 "condition_1" 为False,将判断 "condition_2"
- 如果"condition_2" 为 True 将执行 "statement_block_2" 块语句
- 如果 "condition_2" 为False,将执行"statement_block_3"块语句
注意:
- 每个条件后面要使用冒号 “:”。
- 使用缩进来划分语句块,相同缩进数的语句在一起组成一个语句块。
print("请输入你的年龄:") age = input() if int(age) >= 18: print("恭喜你,你是成年人啦") elif int(age) >= 6: print("你是青少年啦,应该上小学了") else: print("你还是个孩子")
结果如下:

if嵌套
if 表达式1: 语句 if 表达式2: 语句 elif 表达式3: 语句 else: 语句 elif 表达式4: 语句 else: 语句
记录学习笔记,有其他参考,如有侵权,联系删除
本文来自博客园,作者:rissa,转载请注明原文链接:https://www.cnblogs.com/rissa/p/14041916.html

浙公网安备 33010602011771号