使用While循环的猜数字游戏 - Python
我正在尝试制作一个“猜数字(1到10之间)”的游戏,但我的循环似乎一直在运行。我想让程序让用户猜一个数字,然后显示这个数字是太高还是太低,然后自动重新开始(循环),让用户可以再次选择。但是这段代码让它一直运行下去。你们能帮我吗?
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"
4 个回答
0
在编程中,有时候我们需要让程序在特定的条件下执行某些操作。这就像给程序设定了一些规则,只有当这些规则被满足时,程序才会继续进行。
比如说,你可能想要在用户输入的数字大于10时,程序才显示一条消息。这种情况下,你就需要用到“条件语句”。条件语句就像是一个检查点,程序会在这里停下来,看看条件是否成立。如果成立,程序就会执行你设定的操作;如果不成立,程序就会跳过这些操作,继续往下走。
简单来说,条件语句帮助程序根据不同的情况做出不同的反应,就像是生活中的选择一样。
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()
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()
0
如果你把 input
这个语句放到 while 循环里面,就没问题了。
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!"