欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

在Python的while循環(huán)中使用else以及循環(huán)嵌套的用法

 更新時間:2015年10月14日 14:15:26   投稿:goldensun  
這篇文章主要介紹了在Python的while循環(huán)中使用else以及循環(huán)嵌套的用法,是Python入門學(xué)習(xí)中的基礎(chǔ)知識,需要的朋友可以參考下

循環(huán)使用 else 語句
在 python 中,for … else 表示這樣的意思,for 中的語句和普通的沒有區(qū)別,else 中的語句會在循環(huán)正常執(zhí)行完(即 for 不是通過 break 跳出而中斷的)的情況下執(zhí)行,while … else 也是一樣。

#!/usr/bin/python

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

以上實(shí)例輸出結(jié)果為:

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

簡單語句組
類似if語句的語法,如果你的while循環(huán)體中只有一條語句,你可以將該語句與while寫在同一行中, 如下所示:

#!/usr/bin/python

flag = 1

while (flag): print 'Given flag is really true!'

print "Good bye!"

注意:以上的無限循環(huán)你可以使用 CTRL+C 來中斷循環(huán)。

Python 循環(huán)嵌套
Python 語言允許在一個循環(huán)體里面嵌入另一個循環(huán)。
Python for 循環(huán)嵌套語法:

for iterating_var in sequence:
 for iterating_var in sequence:
  statements(s)
 statements(s)

Python while 循環(huán)嵌套語法:

while expression:
 while expression:
  statement(s)
 statement(s)


你可以在循環(huán)體內(nèi)嵌入其他的循環(huán)體,如在while循環(huán)中可以嵌入for循環(huán), 反之,你可以在for循環(huán)中嵌入while循環(huán)。
實(shí)例:
以下實(shí)例使用了嵌套循環(huán)輸出2~100之間的素數(shù):#!/usr/bin/python

# -*- coding: UTF-8 -*-

i = 2
while(i < 100):
j = 2
while(j <= (i/j)):
if not(i%j): break
j = j + 1
if (j > i/j) : print i, " 是素數(shù)"
i = i + 1


print "Good bye!"

以上實(shí)例輸出結(jié)果:

2 是素數(shù)
3 是素數(shù)
5 是素數(shù)
7 是素數(shù)
11 是素數(shù)
13 是素數(shù)
17 是素數(shù)
19 是素數(shù)
23 是素數(shù)
29 是素數(shù)
31 是素數(shù)
37 是素數(shù)
41 是素數(shù)
43 是素數(shù)
47 是素數(shù)
53 是素數(shù)
59 是素數(shù)
61 是素數(shù)
67 是素數(shù)
71 是素數(shù)
73 是素數(shù)
79 是素數(shù)
83 是素數(shù)
89 是素數(shù)
97 是素數(shù)
Good bye!

相關(guān)文章

最新評論