我正在为一款猜谜游戏编写代码,用户可以为该数字选择一个范围,程序将选择一个随机数,并且用户可以猜测该数字,直到正确为止。
我尝试使用条件语句和while循环,但是无法运行它。
if (userGuess > targetNum):
print "\nToo high\n"
elif (userGuess < targetNum):
print "\nToo low\n"
else:
print "\nThat's it! Nice job!\n"
此程序可以运行,但是我需要帮助使其循环运行,以便用户输入自己的猜测并获得反馈(如果它过高或过低,直到他们猜测正确的数字)。谢谢
答案 0 :(得分:0)
您需要确保在成功案例中打破循环
targetNum = 5
while True:
userGuess = int(input("Guess Number"))
if (userGuess > targetNum):
print("\nToo high\n")
continue
elif (userGuess < targetNum):
print("\nToo low\n")
continue
#Break here
else:
print("\nThat's it! Nice job!\n")
break
输出看起来像
Guess Number7
Too high
Guess Number9
Too high
Guess Number12
Too high
Guess Number5
That's it! Nice job!
答案 1 :(得分:0)
添加将由条件触发的布尔值
wrong = True
while(wrong) :
if (userGuess > targetNum):
print "\nToo high\n"
elif (userGuess < targetNum):
print "\nToo low\n"
else:
print "\nThat's it! Nice job!\n"
wrong = False
答案 2 :(得分:0)
您应该将IF语句放在while True:
循环中。
userGuess = float(input("What's your guess? "))
targetNum = 10
while True:
if userGuess > targetNum:
print ("\n Too high\n")
userGuess = float(input("What's your guess? "))
elif userGuess < targetNum:
print ("\n Too low\n")
userGuess = float(input("What's your guess? "))
else:
print ("\n That's it! Nice job! \n")
break