Home > Blockchain >  How do I simplify this python if/elif statement?
How do I simplify this python if/elif statement?

Time:08-24

I'm making a simple rock paper scissors game, and part of the code asks for the user to input at the end if they want to choose to continue to play the game or not, which then breaks out of a while loop or repeats. But the code feels a bit lengthy. Is there any way to make this more efficient?

 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

CodePudding user response:

There are many way to do that. For example you can use regexps:

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

CodePudding user response:

Hi Playsible you could do something like this

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")

CodePudding user response:

Just change element order and use with slicing

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!")

CodePudding user response:

I would convert answers to lowercase and write something like:

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

CodePudding user response:

instead of using

if reset_answer_correct == "YES" or reset_answer_correct == "yes" or reset_answer_correct == "y": continue

use if reset_answer_correct in reset_answer: continue

  • Related