Python学习之条件控制

2021-03-14 04:30

阅读:733

标签:cond   stat   state   condition   info   load   inpu   嵌套   mic   

条件语句是通过一条或多条语句的执行结果(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:
    语句

 

Python学习之条件控制

标签:cond   stat   state   condition   info   load   inpu   嵌套   mic   

原文地址:https://www.cnblogs.com/rissa/p/14041916.html


评论


亲,登录后才可以留言!