代码改变世界

python while for else

2017-11-02 15:57  woodzcl  阅读(228)  评论(0编辑  收藏  举报

python的循环挺有意思

while和for体中可以带上else项

while中的else表示循环条件不成立时,去执行一次,也就是退出循环前去做一次

for中的else表示固定循环正常完成后,去执行一次,也就是正常退出循环前去做一次;但是如果是break方式退出循环的话,就不执行else体了

//test.py

for num in range(10, 20):
  for i in range(2, num):
    if num%i==0:
      j = num/i
      print '%d equal to %d * %d' %(num, i, j)
      break;
  else:
    print num, 'is a prime number'

//result

# python test.py
10 equal to 2 * 5
11 is a prime number
12 equal to 2 * 6
13 is a prime number
14 equal to 2 * 7
15 equal to 3 * 5
16 equal to 2 * 8
17 is a prime number
18 equal to 2 * 9
19 is a prime number

//test.py

count = 0
while count < 5:
  print count, " is less than 5"
  count = count + 1
else:
  print count, " is not less than 5"

//result

# python test.py
0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5

Finally:

各个发明者总是能找到主管的改进点,但是那么多发明者,什么时候才能把这些个点固化下来啊,估计得100年吧

到那时候,编程语言要不很简单,要不重新走上在新的集合下的精简道路。

我觉得这不是个事啊,是否现在大家就坐一起,把这个重新整理一番啊

我个人认为,只要 if while switch就得了吧,这个是被证明完备了的啊。

100年后,是否只有一种语言啊,用这么多语言来浪费生命,失去了意义

但就如同世界上有那么多自然语言一样,什么时候地球各民族成一家啦啊?

NNGQ