Python之While循环语句(实例)#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:
while语句简单例子
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  # 输出双数2、4、6、8、10
i = 1
while True:  # 循环条件为1必定成⽴
print i  # 输出1~10
i += 1
if i > 11:  # 当i⼤于10时跳出循环
实例1:
1、猜拳⼩游戏
#!/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:
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,开始摇⾊⼦:

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。