Python3循環語句


Python3 循環語句

Python中的循環語句有forwhile

循環語句控制結構圖如下:

 

一、while循環

循環結構

while 判斷條件:

執行語句

實例:

n = int(input("請輸入一個數字:"))

sum = 0

counter = 1

while counter <= n:

    sum += counter

    counter += 1

print("1 %d 之和為:%d" % (n,sum))

注意:Python中沒有do...while循環

:無限循環

通過設置條件表達式永遠是True來實現無限循環,實例:

while True :

    num = int(input("請輸入一個數字:"))

    print("你輸入的數字是:",num)

print("Good Bye!")

三、while循環使用else語句

while...else在條件語句為False時執行else的語句塊,實例:

count = 0

while count < 5:

    print(count,"小於5")

    count += 1

else:

    print(count,"大於或等於5")

三、簡單語句組

類似於if語句的語法,如果你的while循環體只有一條語句,你可以將該語句與while寫在同一行中,如下:

while True: print("Hello,World")

    print"Good,Bye"

四、for循環語句

Python for循環可以遍歷任何序列的項目,如一個列表或者一個字符串

for循環的一般格式如下:

for <變量> in <序列>:

    <執行代碼>

else:

    <執行代碼>

循環實例:

scores = [56,76,88,96]

for score in scores:

    if score > = 90:

      print("成績優秀")

    elif score >= 80:

      print("成績良好")

    elif score >= 60:

      print("成績及格")

    else:

      print("成績不及格")

else:

  print("沒有成績")

print("完成循環!")

五、range()函數

利用range()函數可以生成數列,例:

for i in range(5):

  print(i)

# 0 1 2 3 4

也可以使用range指定區間的值:

for i in range(6,10):

  print(i)

#6 7 8 9

也可以在規定區間的時候同時設置增量:

for i in range(0,10,2):

  print(i)

#0 2 4 6 8

負數也可以進行相同操作

for i in range(-10,-100,-20):

  print(i)

#-10 -30 -50 -70 -90

可以結合range()len()函數遍歷一個序列的索引:

list = ["aaa","bbb","ccc","ddd","eee"]

for i in range(len(list)):

  print(i,list[i])

#0 "aaa" 1 "bbb" 2 "ccc" 3 "ddd" 4 "eee"

六、breakcontinue語句及循環中的else子句

break 語句可以跳出forwhile的循環體。如果你從for或者while循環中終止,任何對應的循環else塊將不執行。實例:

for i in 'good':

    if i == "d":

      break

    print("當前字符為:i)

 

continue語句被用來跳過當前循環塊的剩余語句,然后繼續進行下一輪循環。

for i in "good":

    if i == "o":

      continue

    print("當前字母:",i)

循環語句可以有esle子句,它在窮盡列表或條件變為False導致循環終止時被執行,但循環被break終止時不執行。

例:

for n in range(2,10):

    for x in range(2,n):

      print(n,‘等於',x,'*',n//x)

      break

    else:

      print(n,',是質數')

2,是質數

3,是質數

4,等於2*2

5,是質數

6,等於2*3

7,是質數

8,等於2*4

9,等於3*3

七、pass語句

pass是空語句,是為了保持程序結構的完整性。pass不做任何事情,一般用做站位語句,如下實例:

for i in "good":

    if i == "d":

      pass

      print('執行pass')

    print'當前字母:',i

print("Good Bye")


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM