这是我得到的内容,但这只生成一个随机数并无限打印该数:
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))
goto
太近了,令人毛骨悚然。作为每天都在使用古老的Fortran的人,我不想让任何接近goto
的东西玷污Python的美丽... - mgilsonfor
。 - mgilson