MoxieP
MoxieP

Reputation: 11

loop simple calculator: will not loop back to original input

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()

Upvotes: 1

Views: 105

Answers (2)

johnII
johnII

Reputation: 1433

Just use a loop to check for each operation/steps, if valid then proceed if not then just keep looping.

def tryUntilSuccess(prompt,range=None):
    while True:
        try:
            result = int(input(prompt))
            if range and result not in range:
                raise Exception
            else:
                return result
        except:
            print("invalid input. Try again")

def main():
    num1 = tryUntilSuccess("What is number 1?")
    num2 = tryUntilSuccess("What is number 2?")
    operation = tryUntilSuccess("What do you want to do? 1. add, 2. subtract, 3. multiply, or 4. divide. Enter number:", [1,2,3,4])

    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 should not be printed.")
main()

Upvotes: 1

JimmyCarlos
JimmyCarlos

Reputation: 1952

While there are a lot of ways of doing this, this is the probably the way that'll be easiest to understand.

Code:

# 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
    num1,num2,operation = None,None,None
    while not validInput:
        try:
            if num1 is None: num1 = int(input("What is number 1?"))
            if num2 is None: num2 = int(input("What is number 2?"))
            if operation is None: 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()

Upvotes: 0

Related Questions