这就是我所拥有的,但这只会生成一个随机数并无限打印该数字:
import random
x = random.randint(0,10)
y = 7
while x != y:
print(x)
这就是我所拥有的,但这只会生成一个随机数并无限打印该数字:
import random
x = random.randint(0,10)
y = 7
while x != y:
print(x)
类似的东西(在while内移动条件):
stop_at = 7
while True:
num = random.randint(0, 10)
if num == stop_at:
break
print num
或者,一个完整的重构:
from itertools import starmap, repeat, takewhile
from random import randint
for num in takewhile(lambda L: L != 7, starmap(randint, repeat( (0, 10) ))):
print num
你几乎得到它,你需要在循环内生成一个新的随机数:
import random
x = random.randint(0,10)
y = 7
while x != y:
print(x) #Print old (non-7) random number
x = random.randint(0,10) #pick a new number. I hope it's 7 so we can end this madness
print("You found {0}. Congrats. Go have a beer.".format(y))