龙空技术网

Python笔记 while循环,一不小心就循环致死

蚊子不游戏 172

前言:

如今同学们对“python暂停循环”大致比较关注,我们都想要知道一些“python暂停循环”的相关内容。那么小编同时在网上搜集了一些有关“python暂停循环””的相关知识,希望各位老铁们能喜欢,姐妹们快快来了解一下吧!

说实话,今天在写这篇文章的时候就死循环了一回,while真是危险啊。

Python笔记 while循环

while循环经常用来进行重复执行代码,非常好用,但如果用不好也经常容易出错。安全起见,能用for循环还是用for循环吧。

切记当while后的表达式成立时,后面的代码会一直重复运行,直到天荒地老。当出现死循环时用ctrl + c中止程序

python while循环

1. while循环格式

while循环的标准格式如下:

,while expression: code1else: code2

当expression = True时,code1会一直重复执行,如果expression = False才会执行else后的code2。

In [1]:

i = 7while i > 0: print (i, end = ',') i -= 1else: print ('这是else')7,6,5,4,3,2,1,这是else

2. while省略else

else为可选,如果没有else,expression = False时就不执行任何代码。

In [2]:

i = 5while i > 0: print (i, end = ',') i -= 15,4,3,2,1,

3. while循环嵌套

while循环可以嵌套while/for/if等语句实现更复杂的功能。

In [3]:

i = 5while i > 0: i -= 1 while i > 2: print (i, end = ',') i -= 14,3,

4. 死循环

while要形成死循环太容易了,当死循环形成时记得用ctrl + c取消。

要想不形成死循环,一定要要执行前检查while后的expression最终会变成False

while 'python': print ('按ctrl + c 取消,要不然我要一直运行下去')

5. 九九乘法表

用while顺利地手写出一个九九乖法表,说明你的while基本已经掌握了。

In [4]:

a = 1while a <= 9: b = 1 while b <= a: print ('%d * %d = %d' % (a,b,a*b), end = '\t') b += 1 print ('\n') a += 11 * 1 = 1	2 * 1 = 2	2 * 2 = 4	3 * 1 = 3	3 * 2 = 6	3 * 3 = 9	4 * 1 = 4	4 * 2 = 8	4 * 3 = 12	4 * 4 = 16	5 * 1 = 5	5 * 2 = 10	5 * 3 = 15	5 * 4 = 20	5 * 5 = 25	6 * 1 = 6	6 * 2 = 12	6 * 3 = 18	6 * 4 = 24	6 * 5 = 30	6 * 6 = 36	7 * 1 = 7	7 * 2 = 14	7 * 3 = 21	7 * 4 = 28	7 * 5 = 35	7 * 6 = 42	7 * 7 = 49	8 * 1 = 8	8 * 2 = 16	8 * 3 = 24	8 * 4 = 32	8 * 5 = 40	8 * 6 = 48	8 * 7 = 56	8 * 8 = 64	9 * 1 = 9	9 * 2 = 18	9 * 3 = 27	9 * 4 = 36	9 * 5 = 45	9 * 6 = 54	9 * 7 = 63	9 * 8 = 72	9 * 9 = 81	

In [5]:

a = 1while a <= 9: b = 1 while b <= a: print ('%d * %d = %d' % (b,a,a*b), end = '\t') b += 1 print ('\n') a += 11 * 1 = 1	1 * 2 = 2	2 * 2 = 4	1 * 3 = 3	2 * 3 = 6	3 * 3 = 9	1 * 4 = 4	2 * 4 = 8	3 * 4 = 12	4 * 4 = 16	1 * 5 = 5	2 * 5 = 10	3 * 5 = 15	4 * 5 = 20	5 * 5 = 25	1 * 6 = 6	2 * 6 = 12	3 * 6 = 18	4 * 6 = 24	5 * 6 = 30	6 * 6 = 36	1 * 7 = 7	2 * 7 = 14	3 * 7 = 21	4 * 7 = 28	5 * 7 = 35	6 * 7 = 42	7 * 7 = 49	1 * 8 = 8	2 * 8 = 16	3 * 8 = 24	4 * 8 = 32	5 * 8 = 40	6 * 8 = 48	7 * 8 = 56	8 * 8 = 64	1 * 9 = 9	2 * 9 = 18	3 * 9 = 27	4 * 9 = 36	5 * 9 = 45	6 * 9 = 54	7 * 9 = 63	8 * 9 = 72	9 * 9 = 81	

当然也可以用for循环来实现,而且更安全一些:

In [6]:

for a in range(1,10): for b in range(1,10): if a >= b: print ("%d * %d = %d" % (b, a, a*b), end = '\t') print ('\n')1 * 1 = 1	1 * 2 = 2	2 * 2 = 4	1 * 3 = 3	2 * 3 = 6	3 * 3 = 9	1 * 4 = 4	2 * 4 = 8	3 * 4 = 12	4 * 4 = 16	1 * 5 = 5	2 * 5 = 10	3 * 5 = 15	4 * 5 = 20	5 * 5 = 25	1 * 6 = 6	2 * 6 = 12	3 * 6 = 18	4 * 6 = 24	5 * 6 = 30	6 * 6 = 36	1 * 7 = 7	2 * 7 = 14	3 * 7 = 21	4 * 7 = 28	5 * 7 = 35	6 * 7 = 42	7 * 7 = 49	1 * 8 = 8	2 * 8 = 16	3 * 8 = 24	4 * 8 = 32	5 * 8 = 40	6 * 8 = 48	7 * 8 = 56	8 * 8 = 64	1 * 9 = 9	2 * 9 = 18	3 * 9 = 27	4 * 9 = 36	5 * 9 = 45	6 * 9 = 54	7 * 9 = 63	8 * 9 = 72	9 * 9 = 81	

标签: #python暂停循环