Lesson 3-2 语句:循环语句

3.2 循环语句

3.2.1 while 循环语句

--- while 语句包含:关键字while、条件、冒号、while子句(代码块)。

--- 执行while 循环,首先判断条件是否为真,如果为假,结束while循环,继续程序中后面的语句,如果为真,执行while子句的代码块,执行完后调回到while循环开始的地方,重新判断条件是否为真,如果为真,执行while子句的代码块,一遍一遍的循环执行,直至条件为假。

 1 a = 1
 2 while a < 10 :
 3     print(a)
 4     a = a +1
 5 
 6 print('Hello world!')
 7 
 8 结果:
 9 /usr/bin/python3.7 /home/jlu/Projects/Python/untitled/2019-4-21/循环语句.py
10 1
11 2
12 3
13 4
14 5
15 6
16 7
17 8
18 9
19 Hello world!
20 
21 Process finished with exit code 0

&、注意while 语句和if 语句的区别,当条件为真时,while语句执行完一遍后会返回开始点,if 语句执行完一遍后不返回,继续往下执行。

3.2.2 for 循环语句

--- for 语句包含:for 关键字、一个变量名、in关键字、可迭代对象、冒号、for子句(代码块)。

--- for 语句含义:执行迭代(遍历)可迭代对象次数的for子句代码块。

 1 lis = [1, 2, 3, 4, 5]
 2 for i in lis:
 3     print(i)
 4 
 5 total = 0
 6 for num in range(101):
 7     total = total + num
 8 print(total)
 9 
10 结果:
11 /usr/bin/python3.7 /home/jlu/Projects/Python/untitled/2019-4-21/循环语句.py
12 1
13 2
14 3
15 4
16 5
17 5050
18 
19 Process finished with exit code 0
View Code

3.2.3 break 语句

--- break 语句只包含break 关键字,通常放在if 语句的代码块中使用,用于满足一定条件时,立即结束当前迭代,并提前结束循环。

 1 total = 0
 2 for num in range(101):
 3     total = total + num
 4     if total > 2000 :
 5         break
 6 
 7 print(num,total)
 8 
 9 
10 结果:
11 /usr/bin/python3.7 /home/jlu/Projects/Python/untitled/2019-4-21/循环语句.py
12 63 2016
13 
14 Process finished with exit code 0
View Code
 1 total = 0
 2 num = 1
 3 while num < 101 :
 4     total = total + num
 5     num = num +1
 6     if total > 2000 :
 7         break
 8 
 9 print(num,total)
10 
11 
12 结果:
13 /usr/bin/python3.7 /home/jlu/Projects/Python/untitled/2019-4-21/循环语句.py
14 64 2016
15 
16 Process finished with exit code 0
View Code

3.2.4 continue 语句

--- continue 语句只包含continue 关键字,它结束当前迭代,并跳回到迭代开头处,继续进行循环条件判断,条件为真时继续进入循环。

 1 num = 1
 2 while num :
 3     num = num * num + 1
 4     print(str(num) + '-while')
 5     if num < 100 :
 6         continue
 7     print(str(num) + '-continue')
 8     if num > 1000 :
 9         break
10     print(str(num) + '-break')
11 print(str(num) + '-end')
12 
13 
14 结果:
15 /usr/bin/python3.7 /home/jlu/Projects/Python/untitled/2019-4-21/循环语句.py
16 2-while
17 5-while
18 26-while
19 677-while
20 677-continue
21 677-break
22 458330-while
23 458330-continue
24 458330-end
25 
26 Process finished with exit code 0

猜你喜欢

转载自www.cnblogs.com/jlufcs/p/10740129.html
今日推荐