0

I don't know why my try and except isn't working properly. I want it to continue anytime the user inputs either the string "y" or "n", but if the user doesn't input any of those then print the error.

output:

userInput = input("Are both players ready to start? (y/n): ")
k (userInput)
Here we go!

expected output:

userInput = input("Are both players ready to start? (y/n): ")
k (userInput)
Wrong Input, Try Again

try:
  if userInput == "y":
    print("Here we go! ")
    print()
  elif userInput == "n":
    print("Too bad we're starting anyways")
except:
  print("Wrong Input Try Again)
AnonymousC_Lo
  • 61
  • 1
  • 10
  • There is no exception to be thrown if the user adds no input, just neither of your conditions are True. Then there's no outer loop to make it ask again. – roganjosh Dec 04 '18 at 21:48
  • There's a missing string quote, it should read `print("Wrong Input Try Again")`.That's probably not your answer though – Seraf Dec 04 '18 at 21:48
  • just use if, elif, else (don't use try, except). – ctrl-alt-delor Dec 04 '18 at 22:13

2 Answers2

2

There is no error raised in your code, so except is never called. If you want to raise your own exception, use the raise keyword. Details here : https://docs.python.org/2/tutorial/errors.html#raising-exceptions

Axel Puig
  • 1,304
  • 9
  • 19
1

In the try block, you are not raising an error so there is nothing to catch. Adding a raise should do the trick.

userInput = input("Are both players ready to start? (y/n): ")
try:
  if userInput == "y":
    print("Here we go! ")
    print()
  elif userInput == "n":
    print("Too bad we're starting anyways")
  else:
    raise ValueError("What's up with that?")
except:
  print("Wrong Input Try Again")

As suggested by @ctrl-alt-delor you can also skip the try/except block and only use an if/else block. This snippet should do the same:

  if userInput == "y":
    print("Here we go! ")
    print()
  elif userInput == "n":
    print("Too bad we're starting anyways")
  else:
    print("Wrong Input Try Again")
Seraf
  • 850
  • 1
  • 17
  • 34