如果条件问题

huangapple go评论55阅读模式
英文:

If Condition Issues

问题

I have made a simple game for python in a function called (game()). I made an IF condition within a While loop that asks a person if he wants to play the game again (yes=execute game(), no=break) but im facing an issue if the user didnt put neither yes nor no. how do I make it repeat the IF block until the user either put either yes or no. The code is shown as below. Thanks

while True:
     game()
     user=input("Do you want to play again? \n")
     if user=="yes":
        game()
     elif user=="no":
         print("Game is over")
         break
     else:
        print("Please Enter Yes or no")
英文:

I have made a simple game for python in a function called (game()). I made an IF condition within a While loop that asks a person if he wants to play the game again (yes=execute game(), no=break) but im facing an issue if the user didnt put neither yes nor no. how do I make it repeat the IF block until the user either put either yes or no. The code is shown as below. Thanks

`

while True:
     game()
     user=input("Do you want to play again? \n")
     if user=="yes":
        game()
     elif user=="no":
         print("Game is over")
         break
     else:
        ("Please Enter Yes or no") `

答案1

得分: 3

以下是翻译好的部分:

play = "yes"
while play == "yes":
    game()
    play = "unknown"
    while play not in ["yes", "no"]:
        play = input("再玩一次(是/否)?").lower().strip()

这段代码的功能如下:

  • 假设初始 play 值为 yes,以至少玩一次游戏。
  • 确保用户回答 yesno(忽略大小写和前后空格)。
  • 仅在回答为 yes 时继续循环。

如果您决定需要更多功能,可能是将其放入一个辅助函数的时候,可以像这样:

def ask(prompt, allowed):
    resp = input(prompt).lower().strip()
    while resp not in allowed:
        print(f"*** 不是其中之一 [{', '.join(allowed)}]")
        resp = input(prompt).lower().strip()
    return resp

game()
while ask("再玩一次(是/否)?", ["yes", "no"]) == "yes":
    game()

将其放入辅助函数意味着您可以根据需要添加各种功能,可能使用默认值参数,以便最常见的情况不需要额外参数,只需更改一个函数即可。

例如,您可能希望允许不同的后续提示,并决定是否区分大小写:

def _ask_case(value, ignore_case):
    return value.lower() if ignore_case else value

def ask(prompt, allowed, prompt2=None, ignore_case=True):
    if prompt2 is None:
        prompt2 = prompt
    if ignore_case:
        allowed = [item.lower() for item in allowed]
    str_allow = f"*** 不是其中之一 [{', '.join(allowed)}]"

    resp = _ask_case(input(prompt).strip(), ignore_case)
    while resp not in allowed:
        print(str_allow)
        resp = _ask_case(input(prompt2).strip(), ignore_case)

    return resp

我没有测试过这段代码(因此可能无法正常工作),并且可能不是您目前需要的,但是这个想法只是为了显示,将其重构为辅助函数意味着您可以在任何地方使用它,非常简单,但是如果需要的话,仍然具有很大的功能。

英文:

You can do something like:

play = "yes"
while play == "yes":
    game()
    play = "unknown"
    while play not in ["yes", "no"]:
        play = input("Play again (yes/no)? ").lower().strip()

This does the following:

  • Assumes initial play value of yes to play the game at least once.
  • Ensure the user answers yes or no (ignoring case and leading or trailing white space).
  • Continues the loop only for the yes case.

There's improvements you can make if, for example, you want a different message when user enters an invalid response, but that code should be a good start.


If you do decide it needs more features, that's probably when you could argue it would be better in a helper function, something like:

def ask(prompt, allowed):
    resp = input(prompt).lower().strip()
    while resp not in allowed:
        print(f"*** Not one of [{", ".join(allowed)}]")
        resp = input(prompt).lower().strip()
    return resp

game()
while ask("Play again (yes/no)? ", ["yes", "no"]) == "yes":
    game()

Putting it into a helper function means that you can add all sorts of wonderful features as needs require, probably with default-value parameters so the most common case doesn't require them, just by changing that one function.

For example, you may want to allow for a different subsequent prompt and making it case sensitive or not:

def _ask_case(value, ignore_case):
    return value.lower() if ignore case else value

def ask(prompt, allowed, prompt2=None, ignore_case=True):
    if prompt2 is None:
        prompt2 = prompt
    if ignore_case:
        allowed = [item.lower() for item in allowed]
    str_allow = f"*** Not one of [{', '.join(allowed)}]"

    resp = _ask_case(input(prompt).strip(), ignore_case)
    while resp not in allowed:
        print(str_allow)
        resp = _ask_case(input(prompt2).strip(), ignore_case)

    return resp

I haven't tested that code (so it may not work) and it may not be immediately necessary for your purposes, but the idea is just to show that refactoring it into a helper function means you can use it everywhere, and very simply, but still have a lot of power if or when you need it.

答案2

得分: 1

Here's the translated code part:

game() 处于循环的开始位置,循环的每一次迭代都将以此为开始(即重新玩游戏),不管用户在上一次迭代中输入了什么 - 阻止这种情况的唯一方法是通过 break 循环(发生在“no”条件中,但在与无效输入对应的else中没有发生)。

为了解决这个问题,只需将该行移到循环之外:

game()  # 第一次游戏会自动开始,在输入循环开始之前
while True:
     user = input("Do you want to play again? \n")
     if user == "yes":
        game()  # 仅当用户答应时才会进行后续游戏
     elif user == "no":
         print("Game is over")
         break
     else:
        print("Please Enter Yes or no")
英文:

Since game() is at the start of your loop, each iteration of the loop will start with that (i.e. playing the game again), regardless of what the user entered on the previous iteration -- the only way to prevent that is to break the loop (which happens in the "no" condition, but not in the else that corresponds to invalid input).

To fix that, just move that line outside of the loop:

game()  # first game happens automatically, before the input loop starts
while True:
     user=input("Do you want to play again? \n")
     if user=="yes":
        game()  # subsequent games ONLY happen if the user says yes
     elif user=="no":
         print("Game is over")
         break
     else:
        ("Please Enter Yes or no")

答案3

得分: 1

以下是翻译好的内容:

有2个问题我看到了你的代码中:

  • 首先,用户输入需要在它自己的循环内。
  • 如果用户说“是”,你调用游戏两次(一次在if条件返回true后,一次在循环重复后)。

你需要设置一个标志来检查用户输入是否有效。此外,你不希望在检查中调用game()。

while True:
    game()
    
    user = "maybe"
    while user != "no" and user != "yes":
        user = input("你想再玩一次吗?\n")
         
    if user == "no":
        print("游戏结束")
        break
英文:

There are 2 problems I see with your code

  • First is the user input needs to be in its own loop
  • You are calling the game twice if the user says yes (once after the if condition returns true and once more after the loop repeats)

You want to set a flag to check that the user input is valid. Also, you don't want to call game() within the check.

while True:
   game()

   user="maybe"
   while user!="no" and user!="yes":
      user=input("Do you want to play again? \n")
     
   if user=="no":
      print("Game is over")
      break

答案4

得分: 1

为了改进你的代码,请尝试以下方式:

game()
while True:
    user = input("你想再玩一次吗?请输入 yes 或 no\n").lower().strip()
    if user == "yes":
        game()
    elif user == "no":
        print("游戏结束")
        break
    else:
        print("请输入 yes 或 no")
  • 游戏必须在 while 循环之前启动。
  • 用户输入必须不区分大小写。
  • 否则的情况需要使用 print() 函数。
英文:

In order to make your code better, try this:

game()
while True:
     user=input("Do you want to play again? Please Enter yes or no\n").lower().strip()
     if user=="yes":
         game()
     elif user=="no":
         print("Game is over")
         break
     else:
         print("Please Enter yes or no")
  • Game must be started before the while loop
  • User Input must be case-insensitive
  • else row needs print()

huangapple
  • 本文由 发表于 2023年5月18日 06:51:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76276677.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定