如何创建允许用户输入直到在Python中正确为止的循环

2024-09-28 05:28:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为一个猜谜游戏编写一个代码,在这个游戏中,用户可以为要输入的数字选择一个范围,程序将选择一个随机数,用户可以猜到数字,直到他们是正确的

我试过使用条件和while循环,但无法运行它

if (userGuess > targetNum):

    print "\nToo high\n"

elif (userGuess < targetNum):
        print "\nToo low\n"

else:
        print "\nThat's it! Nice job!\n"

这个程序运行,但我需要帮助让它循环,以便用户可以输入他们的猜测,并得到反馈,如果它太高或太低,直到他们猜测正确的数字。谢谢


Tags: 代码用户程序游戏if数字条件low
3条回答

应该将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

添加将由条件触发的布尔值

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 

你需要确保在你成功的时候打破循环

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!

相关问题 更多 >

    热门问题