0

I need users to be able to type x to exit if they get a question wrong.

I've tried changing the input to a string and then if the answer isn't x then convert the string to an integer with int(user_ans) and even making another value and with ans_string == int(user_ans). Is there any way to add a break to the end if they type x?

if level == 1:
    solution = number_one + number_two
    print("What is", number_one, "plus", number_two)
    user_ans = int(input())

if user_ans == solution:
    print("Correct")
    number_one = random.randrange(1,10)
    number_two = random.randrange(1,10)
    rounds = rounds + 1
else:
    print("Try again")

I expect the program to still function but also be for the user to quit.

Ben Jones
  • 15
  • 4

2 Answers2

0

You can first get the user's input into a variable, like with inStr = input('Enter input: '). Then, you can check it to see if it's 'x'; if it is, you can use sys.exit() (or some other function), and if it's not, you can then cast it to a number and use it. inNum = int(inStr)

By checking the variable first and then casting it, you don't have to worry about what happens if your code tries to run int('x').

If you really want to cast your input to int right away, though, you can use try and except to catch a ValueError, which is what int() will throw if you give it a non-number input. This won't specifically check for 'x' - just for some invalid input.

Nick Reed
  • 4,989
  • 4
  • 17
  • 37
0

Just use a try block to see whether the input is a number and change what you do. Something like this:

is_int = false
user_ans = input()

try: 
  ans_int = int(user_ans)
  is_int = true
except:
  is_int = false

if is_int:
  # Do what you need with the integer
  if ans_int == 1:
    solution = number_one + number_two
    print("What is", number_one, "plus", number_two)
    user_ans = int(input())
elif user_ans == solution:
  print("Correct")
  number_one = random.randrange(1,10)
  number_two = random.randrange(1,10)
  rounds = rounds + 1
elif user_ans == "x":
  # Do what you need to do if it is an "x"
else:
   print("Try again")
Akaisteph7
  • 5,034
  • 2
  • 20
  • 43