Python循环语句 python基础之条件循环语句

python基础之条件循环语句

前两篇说的是数据类型和数据运算,本篇来讲讲条件语句和循环语句。

0x00. 条件语句

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

可以通过下图来简单了解条件语句的执行过程:

Flowchart of if...else statement in Python Programming

Python interprets non-zero values as TrueNone and 0 are interpreted as False.

Python 判断非0的值为 True, 而None和0被认为是 False。注意这里的True和False首字母大写,Python对大小写敏感。

条件语句其基本形式为:

1
2
3
4
if  判断条件:
     执行语句……
else
     执行语句……
当判断条件为多个值时,可以使用以下形式:

Flowchart of if...elif....else in python programming

1
2
3
4
5
6
7
8
if  判断条件 1 :
     执行语句 1 ……
elif  判断条件 2 :
     执行语句 2 ……
elif  判断条件 3 :
     执行语句 3 ……
else :
     执行语句 4 ……

0x01. 循环语句

当我们需要执行一个语句或者语句组多次,不可能将同样的语句写多遍,一是比较繁琐, 二是不利于维护,这时候循环语句就应运而生。其中循环语句又分for循环和while循环。

for循环

for循环可以遍历任何序列的项目,如一个列表或者一个字符串。其流程为:

Flowchart of for Loop in Python programming

for循环的语法格式如下:

1
2
for  iterating_var  in  sequence:
    statements(s)
 
     

while循环

while 语句用于循环执行程序,即在某条件下,循环执行某段程序,以处理需要重复处理的相同任务。其流程为:

while Loop in Python programming

while循环的语法格式如下:
1
2
while  判断条件:
     执行语句……
 
     

0x02. 实例

以下实例使用了嵌套循环输出2~100之间的素数:
1
2
3
4
5
6
7
8
9
10
11
12
13
#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
=  2
while (i <  100 ):
    =  2
    while (j < =  (i / j)):
       if  not (i % j):  break
       =  +  1
    if  (j > i / j) :  print  i,  " 是素数"
    =  +  1
 
print  "Good bye!"
上一篇Python系列之 - python运算符

前两篇说的是数据类型和数据运算,本篇来讲讲条件语句和循环语句。

0x00. 条件语句

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

可以通过下图来简单了解条件语句的执行过程:

Flowchart of if...else statement in Python Programming

Python interprets non-zero values as TrueNone and 0 are interpreted as False.

Python 判断非0的值为 True, 而None和0被认为是 False。注意这里的True和False首字母大写,Python对大小写敏感。

条件语句其基本形式为:

1
2
3
4
if  判断条件:
     执行语句……
else
     执行语句……
当判断条件为多个值时,可以使用以下形式:

Flowchart of if...elif....else in python programming

1
2
3
4
5
6
7
8
if  判断条件 1 :
     执行语句 1 ……
elif  判断条件 2 :
     执行语句 2 ……
elif  判断条件 3 :
     执行语句 3 ……
else :
     执行语句 4 ……

0x01. 循环语句

当我们需要执行一个语句或者语句组多次,不可能将同样的语句写多遍,一是比较繁琐, 二是不利于维护,这时候循环语句就应运而生。其中循环语句又分for循环和while循环。

for循环

for循环可以遍历任何序列的项目,如一个列表或者一个字符串。其流程为:

Flowchart of for Loop in Python programming

for循环的语法格式如下:

1
2
for  iterating_var  in  sequence:
    statements(s)
 
   

while循环

while 语句用于循环执行程序,即在某条件下,循环执行某段程序,以处理需要重复处理的相同任务。其流程为:

while Loop in Python programming

while循环的语法格式如下:
1
2
while  判断条件:
     执行语句……
 
   

0x02. 实例

以下实例使用了嵌套循环输出2~100之间的素数:
1
2
3
4
5
6
7
8
9
10
11
12
13
#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
=  2
while (i <  100 ):
    =  2
    while (j < =  (i / j)):
       if  not (i % j):  break
       =  +  1
    if  (j > i / j) :  print  i,  " 是素数"
    =  +  1
 
print  "Good bye!"

猜你喜欢

转载自blog.csdn.net/qq_40285302/article/details/81064579