Home loop simple calculator: will not loop back to original input
Reply: 0

loop simple calculator: will not loop back to original input

user1824
1#
user1824 Published in April 26, 2018, 5:20 pm

Simple calculator. Asks the following:

1) Input for number 1

2) Input for number 2

3) What do you want to do, add/subtract/multiple/divide?

If a user has correct input for Question 1, but incorrect input for Questions 2 or 3, it directs them back to Question 1. I would like to know how invalid input for Question 2 can redirect back to Question 2 so the user may try again. If Question 3 receives invalid input, I would like it to redirect back to Question 3 so the user may try again.

# Returns the sum of num1 and num2
def add(num1, num2):
    return num1 + num2

# returns the results of subtracting num1 - num2
def sub(num1, num2):
    return num1 - num2

# returns the result of multiplying num1 * num2
def mul(num1, num2):
    return num1 * num2

# returns the result of dividing num1/num2
def div(num1, num2):
    try:
        return num1 / num2
    except ZeroDivisionError:
        print("handled div by zero. Returning zero.")
    return 0

def main():
    validInput = False
    while not validInput:
        try:
            num1 = int(input("What is number 1?"))
            num2 = int(input("What is number 2?"))
            operation = int(input("What do you want to do? 1. add, 2. subtract, 3. multiply, or 4. divide. Enter number:"))
            validInput = True
        except:
            print("invalid input. 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")

main()
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.305948 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO