'Input from the use in a try/except block

  1. List item

i want to let the user type 1 , 2 or quit otherwise i want to put him to type again one of them. everything works with 1 and 2 but for quit doesn't work, and i also want if he types quit to use sys.exit('message') - this part is from a function where u can choose your difficulty level. also its a hangman game. tanks

Sloved!!

import sys while True:
difficulty = input("Choose difficulty 1 for easy 2 for hard: ").lower() try:

         if difficulty == '1':
            print('Easy game mode is set!')
         elif difficulty =='2':
            print('Hard game mode is set!')
         elif difficulty =='quit':
            print('Sheeeeeeeeeeeeeeesh')

      except:
         continue
      if difficulty == '1' or difficulty =='2':
         break
      elif difficulty == 'quit':
         sys.exit('byeeeee')
         break
    #elif difficulty 
      else:
         print('invalid ')


Solution 1:[1]

You are storing the user input in uppercase for difficulty variable. And in if condition verifying in lowercase. So remove the upper() from input("Choose difficulty 1 for easy 2 for hard: ").upper()

Solution 2:[2]

try: and except: is probably not what you want to use here because you won't get a ValueError and thus the except does not execute. Maybe try something like:

while True:
    difficulty = input("Choose difficulty 1 for easy 2 for hard: ").upper()
    if difficulty == '1':
        print('Easy game mode is set!')
        break
    elif difficulty =='2':
        print('Hard game mode is set!')
        break
    elif difficulty =='QUIT':
        print('bye')
        break
    else:
        print("you can only choose 1, 2, or quit.")

It breaks the loop when the correct input is given, and keeps looping otherwise.

If you would LIKE to have a ValueError when they enter a wrong input you can use raise like so:

while True:
    difficulty = input("Choose difficulty 1 for easy 2 for hard: ").upper()
    if difficulty == '1':
        print('Easy game mode is set!')
        break
    elif difficulty =='2':
        print('Hard game mode is set!')
        break
    elif difficulty =='QUIT':
        print('bye')
        break
    else:
        print("you can only choose 1, 2, or quit.")
        raise ValueError #notice the additional line here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ratnesh Jaiswal
Solution 2