2014-09-05 61 views
-2

我試圖做一個'猜數字1-10之間的遊戲,但while循環似乎繼續運行。我想編程讓用戶猜測一個數字,然後顯示它是否過高或過低等,然後自動重新啓動(循環)以允許用戶再次選擇。這段代碼使它永遠運行。 你們能幫我嗎?雖然循環猜測數字遊戲 - Python

import random 

def numberGuess(): 
    printNow("I'm thinking of a number between 1 and 10") 
    guess = 0 # give guess a starting value 
    randNum = random.randrange(1,11) # this line generates a random number 
    guess = int(input("Try to guess the number:")) # ask user for a number 
    print randNum 
    while guess != randNum: 
    if (guess == randNum): 
     print "You got it!" 
    if (guess > randNum): 
     print "Wrong! You guessed too high" 
    if (guess < randNum): 
     print "Wrong! You guessed too low" 
+0

你不改變'guess'內環路... – jonrsharpe 2014-09-05 10:25:04

回答

0

如果您將input語句移到while循環中,您應該沒問題。

1

你忘了內環路猜測

while guess != randNum: 
    guess = int(input("Try to guess the number:")) 
    if (guess > randNum): 
     print "Wrong! You guessed too high" 
    if (guess < randNum): 
     print "Wrong! You guessed too low" 
    print "You got it!" 
+0

這段代碼的第一個猜測將不被評估! – user3015703 2014-09-05 10:45:46

+1

@ user3015703,我只指定修改循環。但是在調用循環之前輸入'guess',所以它應該被評估 – 2014-09-05 10:47:48

0

使用此:

import random 

def numberGuess(): 
    print("I'm thinking of a number between 1 and 10") 
    randNum = random.randrange(1,11) # this line generates a random number 
    while guess != randNum: 
    guess = int(input("Try to guess the number:")) # ask user for a number 
    if (guess == randNum): 
     print "You got it!" 
    if (guess > randNum): 
     print "Wrong! You guessed too high" 
    if (guess < randNum): 
     print "Wrong! You guessed too low" 

numberGuess()