我想尝试'猜测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"
你忘了在循环内猜测
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!"
如果你将input
语句移动到while循环中,你应该没问题。
用这个:
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()