2014-09-05 63 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()