Ron Estrada
Ron Estrada

Reputation: 1

Calculator Loop in Python 3

I'm new to programming and I am struggling to make my code loop back to the start so the user can choose another operation without having to restart the program. I know the obvious answer is to add a while loop but I am having trouble implementing this strategy. I was trying to seek help to see what would be the best course of action in order to do this. Thanks.

print('Python Calculator Program')
print('         MENU')
print('1)Add')
print('2)Subtract')
print('3)Multiply')
print('4)Divide')
print('5)Square Root')
print('6)Exit')


print('Enter Your Choice:')
operator=input('Choose a number 1 - 6: ')


while True:
    if operator == '1' or operator == 'Add' or operator == 'add':
        a=float(input('Enter the fist number that you wish to add: '))
        b=float(input('Enter the second number that you wish to add: '))

        ans=sum(a,b)
        print('The sum of the numbers are: ', ans)

    elif operator == '2' or operator == 'Subtract' or operator == 'subtract':
        a=float(input('Enter the fist number that you wish to subtract: '))
        b=float(input('Enter the second number that you wish to subtract: '))

        ans=difference(a,b)
        print('The difference of the numbers are: ', ans)

    elif operator == '3' or operator == 'Multiply' or operator == 'multiply':
        a=float(input('Enter the fist number that you wish to multiply: '))
        b=float(input('Enter the second number that you wish to multiply: '))

        ans=product(a,b)
        print('The product of the numbers are: ', ans)

    elif operator == '4' or operator == 'Divide'  or operator == 'divide':
        a=float(input('Enter the dividend: '))
        b=float(input('Enter the divisor: '))

        ans=quotient(a,b)
        print('The quotient of the numbers are: ', ans)

    elif operator == '5' or operator == 'Square Root' or operator == 'sqaure root':
        a=float(input('Enter the number you wish to find the square root of: '))

        ans=sqrt(a)
        print('The square root of the number is: ', ans)

    elif operator =='6':
        print('CALCULATOR: ON [OFF]')
        break


    else:
        print('Enter the math operator as dislayed')
        operator=input('Choose an operator: ')





def sum(a,b):
    return a+b

def difference(a,b):
    return a-b

def product(a,b):
    return a*b

def quotient(a,b):
    return a/b

def sqrt(a):
    import math
    return(math.sqrt(a))

main()

Upvotes: 0

Views: 2572

Answers (3)

Yonatan Zax
Yonatan Zax

Reputation: 39

I had a code very similar to what you need. Note that you didn't check for a valid input from the user.

hope it helps

import math



def isfloat(value):
  """
    Checks if the given value represent float
  :param value:
  :return: True if float
  """
  try:
    float(value)
    return True
  except:
    return False



def chooseOperator(input):
    # Returns a method to run
    return {

        '1': oneAdd,
        'add': oneAdd,
        '2': twoDif,
        'subtract': twoDif,
        '3': threeMult,
        'multiply': threeMult,
        '4': fourDiv,
        'divide': fourDiv,
        '5': fiveSqrt,
        'sqaure root': fiveSqrt,
        '6': sixExit,
        'exit': sixExit

    }[input]


def printMenu():
    print('\n\t--  MENU  --')
    print('1)\t Add')
    print('2)\t Subtract')
    print('3)\t Multiply')
    print('4)\t Divide')
    print('5)\t Square Root')
    print('6)\t Exit')




def mainLoop():
    inputFromUser = True
    print('\n\n**   Python Calculator Program   **')
    print('CALCULATOR: [ON] OFF')


    while inputFromUser:
        # Prints the menu to the console
        printMenu()

        try:
            # operator is a function
            operator = chooseOperator((input('Choose an operator:  ')).lower())
            # inputFromUser is a boolean variable
            inputFromUser = operator()

        except KeyError:
            # Unknown input
            print('\n\t Please choose an operator from the menu')




def oneAdd():
    # Get input from user
    a = input('Enter the first number that you wish to add: ')
    b = input('Enter the second number that you wish to add: ')

    # Check that the input is valid
    if isfloat(a) and isfloat(b):
        # Calculate with values
        ans = float(a) + float(b)
        print('The sum of the numbers are: ', ans)


    else:
        # Notify the user that the values are not valid
        print("\tInvalid values:")
        print("\t\tfirst  = ", a)
        print("\t\tsecond = ", b)

    return True


def twoDif():
    # Get input from user
    a = input('Enter the first number that you wish to subtract: ')
    b = input('Enter the second number that you wish to subtract: ')

    # Check that the input is valid
    if isfloat(a) and isfloat(b):
        # Calculate with values
        ans = float(a) - float(b)
        print('The difference of the numbers are: ', ans)


    else:
        # Notify the user that the values are not valid
        print("\tInvalid values:")
        print("\t\tfirst  = ", a)
        print("\t\tsecond = ", b)


    return True


def threeMult():
    # Get input from user
    a = input('Enter the first number that you wish to multiply: ')
    b = input('Enter the second number that you wish to multiply: ')

    # Check that the input is valid
    if isfloat(a) and isfloat(b):
        # Calculate with values
        ans = float(a) * float(b)
        print('The product of the numbers are: ', ans)

    else:
        # Notify the user that the values are not valid
        print("\tInvalid values:")
        print("\t\tfirst  = ", a)
        print("\t\tsecond = ", b)

    return True


def fourDiv():
    # Get input from user
    a = input('Enter the dividend: ')
    b = input('Enter the divisor: ')

    # Check that the input is valid
    if isfloat(a) and isfloat(b):
        # Calculate with values
        ans = float(a) / float(b)
        print('The quotient of the numbers are: ', ans)

    else:
        # Notify the user that the values are not valid
        print("\tInvalid values:")
        print("\t\tfirst  = ", a)
        print("\t\tsecond = ", b)

    return True


def fiveSqrt():
    # Get input from user
    a = input('Enter the number you wish to find the square root of: ')

    # Check that the input is valid
    if isfloat(a):
        # Calculate with values
        ans = math.sqrt(float(a))
        print('The square root of the number is: ', ans)

    else:
        # Notify the user that the values are not valid
        print("\tInvalid value:")
        print("\t\tfirst  = ", a)

    return True


def sixExit():
    print('\n\nCALCULATOR: ON [OFF]')
    return False





if __name__ == '__main__':

    mainLoop()

Upvotes: 0

Grimmpier
Grimmpier

Reputation: 74

To answer your original question, you have to re-prompt every time the program loops around, so you'll want to put the prompt inside the loop. I know you say you're new to coding, so I took the time to go through your code and fix/comment some things to hopefully help you do things more efficiently

import math

def sum(a,b): return a+b

def difference(a,b): return a-b

def product(a,b): return a*b

def quotient(a,b): return a/b

def sqrt(a): return(math.sqrt(a))

def selectMenu():
    print('Python Calculator Program')
    print('         MENU')
    print('1)Add')
    print('2)Subtract')
    print('3)Multiply')
    print('4)Divide')
    print('5)Square Root')
    print('6)Exit')
    print('Enter Your Choice:')
    return input('Choose a number 1 - 6: ')


def main():
ans = "" #declare ans because if we try to see if ans == "" and ans doesnt exist, the 
         #program will crash
operator = "" # "" is not 6, therefore the while loop will run at least once
while operator != '6': #as long as the variable operator is not 6  // operator != '6' 
                       #is your condition
    operator = selectMenu() #this will get the user's choice
    operation = "" #our placeholder for the operation string
    if operator == '1' or operator.lower() == 'add': #.lower() will convert the 
                                                     #entire string to lowercase, so 
                                                     #that you dont have to test for                                                          
                                                     #caps
        a=float(input('Enter the fist number that you wish to add: '))
        b=float(input('Enter the second number that you wish to add: '))
        operation = "sum"
        ans= sum(a,b)

    elif operator == '2' or operator.lower() == 'subtract':
        a=float(input('Enter the fist number that you wish to subtract: '))
        b=float(input('Enter the second number that you wish to subtract: '))
        operation = "difference"
        ans = difference(a, b)


    elif operator == '3' or operator.lower() == 'multiply':
        a=float(input('Enter the fist number that you wish to multiply: '))
        b=float(input('Enter the second number that you wish to multiply: '))
        operation = "product"
        ans=product(a,b)

    elif operator == '4' or operator.lower() == 'divide':
        a=float(input('Enter the dividend: '))
        b=float(input('Enter the divisor: '))
        operation = "quotient"
        ans=quotient(a,b)


    elif operator == '5' or operator.lower() == 'square root':
        a=float(input('Enter the number you wish to find the square root of: '))
        operation = "square root"
        ans=sqrt(a)

    elif operator =='6':
       print('CALCULATOR: ON [OFF]')
       operation = ""
       ans = ""
       #break // while break technically works, its a bad habit to get in to. your 
       #loops should naturally terminate themselves by causing the condition to 
       #become false

    else:
        print('Enter the math operator as displayed')

         if ans != "": # since we're always gonna print the answer no matter what 
                       #they pick, its easier to do it after your if statements.
             print() #print empty lines for spacing
             print("The ", operation, " is: ", ans)
             print()

 main()

Upvotes: 1

Reedinationer
Reedinationer

Reputation: 5774

I think your code indentation is off in your post but I imagine you are just looking to ask the user for input each loop in which case you can simply move your line of code

while True:
    operator=input('Choose a number 1 - 6: ')
    if operator == '1' or operator == 'Add' or operator == 'add':
..... # all your other code

Upvotes: 1

Related Questions