0

I recently started trying to learn how to code and I was excited that I was putting together a super basic calculator, but I have painted myself into a corner that I do not know how to get out of, due mainly to my lack of knowledge. I am using the try: except: block to prevent people from typing in letters but doing so prevents me from being able to type q to quit.

answer = 0

while True:
    print(f"Give me a number: (Saved Value: {answer})\n('q' to quit)")
    try:
        num1 = float(input("> "))
    except ValueError:
        if num1 == 'q':
            break
    else:
        print("Numbers only please!\n")
        continue
    
    print(f"Give me another number: (Saved Value: {answer})\n('q' to quit)")
    try:
        num2 = float(input("> "))
    except ValueError:
        if num2 == 'q':
            break
    else:
        print("Numbers only please!\n")
        continue

    print(f"Give me an operator: (+, -, /, *) (Saved Value: {answer})\n('q' to quit)")
    my_math = input("> ")
    if my_math == 'q':
        break

    if my_math == '+':
        print(num1 + num2)
        answer = num1 + num2
        answer = answer
    elif my_math == '-':
        print(num1 - num2)
        answer = num1 - num2
        answer = answer
    elif my_math == '/':
        print(num1 / num2)
        answer = num1 / num2
        answer = answer
    elif my_math == '*':
        print(num1 * num2)
        answer = num1 * num2
        answer = answer
Random Davis
  • 6,662
  • 4
  • 14
  • 24
Paqman
  • 1
  • 5
    You have to *first* check whether the user input is "q" and *then* try to convert it to a number. – mkrieger1 Mar 09 '22 at 16:41
  • You should look at the answers to this [question](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – quamrana Mar 09 '22 at 16:43
  • If `float()` gets an error, the assignment to `num1` never happens, so you can't compare it with `q` to see what they actually typed. – Barmar Mar 09 '22 at 17:26

1 Answers1

0

This should work as you intended if you indent both occurrences of

else:
    print("Numbers only please!\n")
    continue

to be in line with the if statements.

MiniEggz
  • 55
  • 9