#while 循環
numbers=[1,2,4,6,7,8,12] enent=[] odd=[] while len(numbers) > 0: number=numbers.pop() if(number % 2 == 0): enent.append(number) print number, '是偶數'
print numbers else: odd.append(number) print number,'不是偶數'
print enent print odd # continue 和 break 用法 #continue 用於跳過該次循環, # break 則是用於退出循環, # 此外"判斷條件"還能夠是個常值,表示循環一定成立
i = 1
while i < 10: i += 1
if i % 2 > 0: # 非雙數時跳過輸出
continue
print i # 輸出雙數二、四、六、八、10
i = 1
while True: # 循環條件爲1一定成立
print i # 輸出1~10
i += 1
if i > 11: # 當i大於10時跳出循環
實例1:python
一、猜拳小遊戲
#!/usr/bin/python # -*- coding: UTF-8 -*- import random while 1: 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 not in blist) and (m != 'end'): print "輸入錯誤,請從新輸入!" elif (m not in blist) and (m == 'end'): print "\n遊戲退出中..." break elif 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"結束遊戲:
實例2:app
2、搖色子游戲 #coding=utf-8 #!/usr/bin/python import random import sys import time result = [] #print type(inss) while True: inss = int(raw_input("輸入一個1,開始搖色子:")) if inss ==1: 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 += "," #pointStr +=str(pointStr) #print str(currPoint) #print pointStr if count <= 11: print result,"-->小" time.sleep( 1 ) # 睡眠一秒 else: print result,"-->大" time.sleep( 1 ) # 睡眠一秒 else: print "你輸入的字符不對噢" result = []
執行結果:
輸入一個1,開始搖色子:1 [1, 5, 6] [1, 5, 6] -->大 輸入一個1,開始搖色子:2 你輸入的字符不對噢 輸入一個1,開始搖色子: