1

I apologize for my lack of knowledge. I have just started learning python and I created a basic calculator using a youtube video. It's something like this:

user_continue = True
while user_continue:
    validInput = False
    while not validInput:
        # Get user input
        try:
            num1 = int(input("What is number 1?"))
            num2 = int(input("What is number 2?"))
            operation = int(input("What do you want to do with these? 1. add, 2. subtract, 3. multiply 4. divide. Enter number:"))
            validInput = True
        except:
            print("Invalid Input. Please try again.")
    if(operation == 1):
        print("Adding...")
        print(add(num1, num2))
    elif(operation == 2):
        print("Subtracting...")
        print(sub(num1, num2))
    elif(operation == 3):
        print("Multiplying...")
        print(mul(num1, num2))
    elif(operation == 4):
        print("Dividing...")
        print(div(num1, num2))
    else:
        print("I don't understand. Please try again.")
    user_yn = input('Would you like to do another calculation? ("y" for yes or any other value to exit.)')
    if(user_yn == 'y'):
        continue
    else:
        break

What I want to do is, I want the program to ask for another input for "operation" if the user inputs a number different than 1,2,3 or 4.

Again I apologize for anything wrong, I have just started.

harikaerif
  • 11
  • 1
  • 2
  • [Asking the user for input until they give a valid response](https://stackoverflow.com/q/23294658/953482) may be useful here. – Kevin May 10 '18 at 16:21
  • `user_continue` and `user_yn` should be combined into one variable – Nir Alfasi May 10 '18 at 16:22
  • `if operation > 4 or operation < 0 : validinput = False` but I suggest separating it to two loops, one for getting numbers and other for operations – shahaf May 10 '18 at 16:23
  • Your "go back a step" operation is what's commonly referred to as a [GoTo](https://en.wikipedia.org/wiki/Goto), probably the most hated operation in any programming language. It is not supported in Python, you must use other methods like loops. – poompt May 10 '18 at 16:25
  • You go back by using loops, like those `while` loops you have. – interjay May 10 '18 at 16:25

3 Answers3

1

Using your existing code a simple change will work:

while not validInput:
    # Get user input
    try:
        num1 = int(input("What is number 1?"))
        num2 = int(input("What is number 2?"))
        operation = int(input("What do you want to do with these? 1. add, 2. subtract, 3. multiply 4. divide. Enter number:"))
        if 1 <= operation <=4:
            validInput = True
        else:
            print("Invalid Input. Please try again.")
    except:
        print("Invalid Input. Please try again.")
jonyfries
  • 772
  • 6
  • 20
1

This is a quite simple modification. Here in your code:

    operation = int(input("What do you want to do with these? 1. add, 2. subtract, 3. multiply 4. divide. Enter number:"))
    validInput = True

You should simply check if the input is valid before you flag validInput to be True. To continue to utilize your try-except block, you can check this using assertions like so:

    operation = ...
    assert operation in (1,2,3,4)
    validInput = True

If operation is not in (1,2,3,4) then the code will throw an AssertionError which your try-except block will catch.

On an unrelated note, you probably should not use an except clause that catches all errors like you are doing here. Indeed, this block will catch a KeyboardInterrupt error as well which means you won't be able to exit out of the program! Better to use except ValueError and except AssertionError

enumaris
  • 1,868
  • 1
  • 16
  • 34
0

Functions are your friend. This one will only return 1-4, looping internally until the input is correct. break exits the infinite while loop. If an integer is not entered, a ValueError is thrown and the except clause ignores it. Anything invalid will print "Invalid input" and continue to loop.

def get_operation():
    while True:
        try:
            op = int(input('Enter 1-add, 2-subtract, 3-muliply, 4-divide: '))
            if 1 <= op <= 4:
                break
        except ValueError:
            pass
        print('Invalid input')
    return op

operation = get_operation()
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251