我正在尝试'猜测1-10之间的数字'游戏,但是while循环似乎继续运行。我想编程让用户猜一个数字然后显示它是否太高或太低然后再次自动启动(循环)以允许用户再次选择。这段代码使它永远运行。 你能帮助我吗?
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 :(得分:2)
你忘了在循环内猜测
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!"
答案 1 :(得分:0)
如果将input
语句移动到while循环中,则应该没问题。
答案 2 :(得分:0)
import random
def numberGuess():
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 True:
if (guess == randNum):
print ("You got it!")
break
if (guess > randNum):
print ("Wrong! You guessed too high")
guess = int(input("Try to guess the number:")) # ask user for a number
if (guess < randNum):
print ("Wrong! You guessed too low")
guess = int(input("Try to guess the number:")) # ask user for a number
numberGuess()