2012-11-01 35 views

回答

2

你已經基本得到它,你需要生成循環內一個新的隨機數:

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)) 
6

喜歡的東西(移動狀態,而內):

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 
+0

我總是在這一個撕裂。我應該創建一個有中斷的無限循環,還是應該展開循環的第一個迭代並放在之前? ...這讓我希望Python有一個「直到」其他語言的聲明。 – mgilson

+0

@mgilson或者在任意點而不是從條件開始循環的方法。這解決了部分第一次或最後一次迭代的更一般情況。 – agf

+0

@mgilson是的,我總是被撕裂 - 可以重新做一個for,這使得條件更清晰...(有點 - 看例子) –