Python's conditional control

if...else

Because the computer can judge for themselves the conditions to do, so do many automation tasks.

such as

1 if condition_1:
2     statement_block_1
3 elif condition_2:#elif相当于else if
4     statement_block_2
5 else:
6     statement_block_3

 

  • If "condition_1" to True will perform "statement_block_1" block statements
  • If "condition_1" to False, the judge "condition_2"
  • If "condition_2" to True will perform "statement_block_2" block statements
  • If "condition_2" to False, will perform "statement_block_3" block statements

if ... else statement as to the possible, increase the number of elif do more detailed classification. Executed from top to bottom, when the condition of the old ignore the rest of the elif and else, even if the following conditions are satisfied.

note:

  • 1, each of the conditions to be used later in the colon  : indicates the following condition is satisfied after the statement block to be executed.
  • 2, using indentation divided statement blocks, the number of statements in the same indentation together to form a block.
  • 3, there is no switch in Python - case statement.

 

 

if nested

 可以把if..elif..else结构放在另一个if...elif...else结构中。

 1 #!/usr/bin/env python3
 2 #-*- coding: utf-8 -*-
 3 num=int(input("输入一个数字:"))#input()获取的数据是字符串,需要转化成数字类型,才可以进行下面的比较操作
 4 if num%2==0:
 5     if num%3==0:
 6         print ("你输入的数字可以整除 2 和 3")
 7     else:
 8         print ("你输入的数字可以整除 2,但不能整除 3")
 9 else:
10     if num%3==0:
11         print ("你输入的数字可以整除 3,但不能整除 2")
12     else:
13         print  ("你输入的数字不能整除 2 和 3")

 

 结果:

1 输入一个数字:7
2 你输入的数字不能整除 2 和 3
3 
4 进程已结束,退出代码0

 

Guess you like

Origin www.cnblogs.com/zhangyanlong/p/11306952.html