if控制流语句执行条件原理



if语句也叫做控制流语句,给出条件来决定下一步应该怎么操作。其实原理就是如果条件为真,则执行语句块内容被执行;如果条件为假,则语句块就不会被执行。





Python条件语句是通过一条或多条语句的执行结果(True或者False)来决定执行的代码块。

if控制流语句的语法


if condition_1:
    statement_block_1
elif condition_2:
    statement_block_2
else:
    statement_block_3


1)如果 "condition_1" 为 True 将执行 "statement_block_1" 块语句;

2)如果 "condition_1" 为False,将判断 "condition_2";

3)如果"condition_2" 为 True 将执行 "statement_block_2" 块语句;

4)如果 "condition_2" 为False,将执行"statement_block_3"块语句;



Python 中用 elif 代替了 else if,所以if语句的关键字为:if – elif – else。

实例



实例1

age = int(input("请输入你家狗狗的年龄: "))
print("")
if age < 0:
    print("你是在逗我吧!")
elif age == 1:
    print("相当于 14 岁的人。")
elif age == 2:
    print("相当于 22 岁的人。")
elif age > 2:
    human = 22 + (age -2)*5
    print("对应人类年龄: ", human)



实例2

people = 30
cars = 40
buses = 15


if cars > people: 
  print("We should take the cars.")
elif cars < people: 
  print("We should not take the cars.")
else: 
  print("We can't dicide.")


if buses > cars: 
  print "That's too many buses."
elif buses < cars: 
  print("Maybe we could take the buses.")
else: 
  print("We still can't decide.")


if people > buses: 
  print("Alright, let's just take the buses.")
else: 
  print("Fine, let's stay home then.")



实例3

num = int(input("enter number"))
if num%2 == 0:
    if num%3 == 0:
        print ("Divisible by 3 and 2")
    else:
        print ("divisible by 2 not divisible by 3")
else:
    if num%3 == 0:
        print ("divisible by 3 not divisible by 2")
    else:
        print  ("not Divisible by 2 not divisible by 3")
right