簡體   English   中英

如何簡化此 python if/elif 語句?

[英]How do I simplify this python if/elif statement?

我正在制作一個簡單的石頭剪刀布游戲,部分代碼要求用戶在最后輸入他們是否要選擇繼續玩游戲,然后打破一個while循環或重復。 但是代碼感覺有點冗長。 有什么辦法可以提高效率嗎?

 reset_answer = ["YES", "NO", "no", "yes", "y", "n"]
reset_answer_correct = None
while reset_answer_correct not in reset_answer:
    reset_answer_correct = input("That was fun! would you like to play again? Yes or no: ")
if reset_answer_correct == "YES" or reset_answer_correct == "yes" or reset_answer_correct == "y":
    continue
elif reset_answer_correct == "NO" or reset_answer_correct == "no" or reset_answer_correct == "n":
    print("Thanks for playing!")
    break

有很多方法可以做到這一點。 例如,您可以使用正則表達式:

import re

positive_answer = r"y(?:es)?"
negative_answer = r"no?"

def wanna_continue():
  while True:
    answer = input('That was fun! would you like to play again? Yes or no: ')
    if re.fullmatch(positive_answer, answer, re.I):
      return True
    if re.fullmatch(negative_answer, answer, re.I):
      return False

...

if wanna_continue():
  continue
else:
  print("Thanks for playing!")
  break

嗨 Playsible 你可以做這樣的事情

action=None
exit_options = ["NO", "no","n"]
continue_options = ["Yes", "yes", "y"]
while action not in exit_options:
    action = input("Would you like to play? Yes or no: ")
    if action not in exit_options+continue_options:
        print("Invalid option")
print("Thank you for playing")

我會將答案轉換為小寫並編寫如下內容:

NO_ANSWERS = ["no", "n"]

answer = None
while answer not in ["yes", "y"] + NO_ANSWERS:
    answer = (
        input("That was fun! would you like to play again? Yes or no: ").strip().lower()
    )

if answer in NO_ANSWERS:
    print("Thanks for playing!")
    break
continue

只需更改元素順序並與切片一起使用

reset_answer = ["YES", "yes", "y", "NO", "no", "n"]
reset_answer_correct = None
while reset_answer_correct not in reset_answer:
    reset_answer_correct = input("That was fun! would you like to play again? Yes or no: ")
    if reset_answer_correct in reset_answer[3:]:
        print("Thanks for playing!")

而不是使用

如果 reset_answer_correct == "YES" 或 reset_answer_correct == "yes" 或 reset_answer_correct == "y": 繼續

在 reset_answer 中使用 if reset_answer_correct: continue

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM