一、計算階乘:1*2*3*4*...*n
for迴圈計算階乘的方式:
結果是:#fo***ct.py
n=int(input('enter an integer>=0:'))
fact=1
for i in range(2,n+1):
fact=fact*i
print(str(n)+' factorial is '+ str(fact))
>>>
enter an integer>=0:10
10 factorial is 3628800
while迴圈計算階乘的方式:
結果是:#whilefact.py
n=int(input('enter an integr >=0: '))
fact=1
i=2while i<=n:
fact=fact*i
i=i+1
print(str(n)+' factorial is '+str(fact))
>>>
enter an integr >=0: 10
10 factorial is 3628800
二、計算使用者輸入的數字的總和
下面程式是讓使用者輸入一些數字,然後列印出這些數字的總和,下面是for迴圈的案例:
結果是:#forsum.py
n=int(input('how many numbers to sum?'))
total=0
for i in range(n):
s=input('enter number '+str(i+1)+': ')
total=total+int(s)
print('the sum is '+str(total))
>>>
how many numbers to sum?4
enter number 1: 24
enter number 2: 22
enter number 3: 46
enter number 4: 56
the sum is 148
再次測試一下while迴圈:
結果如下:#whilesum.py
n=int(input('how many numbers to sum? '))
total=0
i=1while i<=n:
s=input('enter number '+str(i)+': ')
total=total+int(s)
i=i+1
print('the sum is '+str(total))
>>>
how many numbers to sum? 3
enter number 1: 49
enter number 2: 89
enter number 3: 26
the sum is 164
三、計算未知個數字的總和
假設輸入一系列數字,使用者輸入'done'的時候就對相應前面輸入的數字進行求和,程式是:
結果如下:#donesum.py
total=0
s=input('enter a number (or "done"): ')
while s!='done':
num=int(s)
total=total+num
s=input('enter a number (or "done"): ')
print('the sum is '+str(total))
>>>
enter a number (or "done"): 23
enter a number (or "done"): 45
enter a number (or "done"): 78
enter a number (or "done"): done
the sum is 146
該程式基本思想是:不斷要求使用者輸入數字,直到使用者輸入'done'才罷手。該程式預先不知道迴圈體將執行多少次。
注意:該程式必須在兩個地方呼叫input:迴圈體前面和迴圈體內,之所以這樣操作,使因為迴圈條件判斷輸入的是數字還是'done'.
不需要使用到計算器變數i。在前面計算總和的程式中,i用於記錄使用者輸入多少數字,但此處不需要。
四、跳出迴圈和語句塊
break語句能夠從迴圈體內的任何地方跳出迴圈,如:
結果是:#donesum_break.py
total=0
while true:
s=input('enter a number (or "done"): ')
if s=='done':
break # jump out of the loop
num=int(s)
total=total+num
print('the sum is '+str(total))
>>>
enter a number (or "done"): 35
enter a number (or "done"): 38
enter a number (or "done"): 98
enter a number (or "done"): 90
enter a number (or "done"): 78
enter a number (or "done"): 27
enter a number (or "done"): done
the sum is 366
while迴圈條件為true的時候,將永遠迴圈下去,直到break被執行。
僅當s為done的時候,break才被執行。
一般而言,除非break語句讓**更簡單或更清晰,否則不要使用它。
乙個與break語句相關的是continue語句:在迴圈體中呼叫continue語句時候,將立即轉到迴圈條件,即進入下乙個迭代,但程式設計過程中,盡量避免使用continue語句。
python入門 認識while迴圈及運用
本節內容 1 認識while迴圈 2 while迴圈的運用 3 巢狀迴圈 迴圈套迴圈 1 認識while迴圈 break 跳出當前整個迴圈 continue 跳出當次迴圈,繼續下次迴圈 1 while 判斷條件 當while滿足條件時,程式會一直迴圈 2執行語句.3else 當while正常迴圈完成...
Python入門例項驗證及結果之例項1 溫度轉化
2020年1月28日星期二 例項1 溫度轉化 tempconvert.py tempstr input 請輸入帶有符號的溫度值 if tempstr 1 in f f c eval tempstr 0 1 32 1.8print 轉換後的溫度值為c format c elif tempstr 1 i...
Python迴圈操作
coding utf 8 created on 2016年12月21日 author administrator 分別用for迴圈和while迴圈實現列表元素的翻倍 def create list n data i 0 while i n print enter item x int raw inp...