1. 程式人生 > >python中的while語句

python中的while語句

迴圈使用 else 語句

在 python 中,while … else 在迴圈條件為 false 時執行 else 語句塊:

例項

#!/usr/bin/python count = 0 whilecount < 5:   printcount, " is less than 5" count = count + 1 else:   printcount, " is not less than 5"

以上例項輸出結果為:

0is less than 51is less than 52is less than 53is less than 54is less than 
55isnot less than 5
numbers=[1,2,3,4,5]

even=[ ]

odd=[ ]

while len(numbers)>0:

        number=numbers.pop()

     if(number%2==0):

       even.append(number)

    else:

       odd.append(number)

猜大小的遊戲

#!/usr/bin/python# -*- coding: UTF-8 -*-import random
s =int(random.uniform(1,10))#print(s)
m 
=int(input('輸入整數:'))while m != s:if m > s:print('大了')         m =int(input('輸入整數:'))if m < s:print('小了')         m =int(input('輸入整數:'))if m == s:print('OK')break;

猜拳小遊戲

#!/usr/bin/python# -*- coding: UTF-8 -*-import random
while1:
    s =int(random.randint(1,3))if s ==1:
        ind ="石頭"elif s 
==2: ind ="剪子"elif s ==3: ind ="布" m = raw_input('輸入 石頭、剪子、布,輸入"end"結束遊戲:') blist =['石頭',"剪子","布"]if(m notin blist)and(m !='end'):print"輸入錯誤,請重新輸入!"elif(m notin blist)and(m =='end'):print"\n遊戲退出中..."breakelif m == ind :print"電腦出了: "+ ind +",平局!"elif(m =='石頭'and ind =='剪子')or(m =='剪子'and ind =='布')or(m =='布'and ind =='石頭'):print"電腦出了: "+ ind +",你贏了!"elif(m =='石頭'and ind =='布')or(m =='剪子'and ind =='石頭')or(m =='布'and ind =='剪子'):print"電腦出了: "+ ind +",你輸了!"

測試結果:

輸入石頭、剪子、布,輸入"end"結束遊戲:石頭電腦出了:石頭,平局!輸入石頭、剪子、布,輸入"end"結束遊戲:石頭電腦出了:剪子,你贏了!輸入石頭、剪子、布,輸入"end"結束遊戲:

搖篩子游戲

#!/usr/bin/env python3# -*- coding: utf-8 -*-import random
import sys
import time

result =[]whileTrue:
    result.append(int(random.uniform(1,7)))
    result.append(int(random.uniform(1,7)))
    result.append(int(random.uniform(1,7)))print result
    count =0
    index =2
    pointStr =""while index >=0:
        currPoint = result[index]
        count += currPoint
        index -=1
        pointStr +=" "
        pointStr += str(currPoint)if count <=11:
        sys.stdout.write(pointStr +" -> "+"小"+"\n")
        time.sleep(1)# 睡眠一秒else:
        sys.stdout.write(pointStr +" -> "+"大"+"\n")
        time.sleep(1)# 睡眠一秒
    result =[]

十進位制轉二進位制

#!/usr/bin/python# -*- coding: UTF-8 -*-

denum = input("輸入十進位制數:")print denum,"(10)",
binnum =[]# 二進位制數while denum >0:
    binnum.append(str(denum %2))# 棧壓入
    denum //= 2print'= ',while len(binnum)>0:import sys
    sys.stdout.write(binnum.pop())# 無空格輸出print ' (2)'

while迴圈 - 九九乘法表

#!/usr/bin/python# -*- coding: UTF-8 -*-#九九乘法表

i =1while i :
    j =1while j:print j ,"*", i ," = ", i * j ,'  ',if i == j :break

        j +=1if j >=10:breakprint"\n"
    i +=1if i >=10:break
這是一些部落格主提供的非常好的例子值得借鑑學習。