Python 3中的计算器循环

时间:2019-02-13 20:10:58

标签: python loops while-loop

我是编程新手,我正努力使我的代码循环回到起点,以便用户可以选择其他操作,而不必重新启动程序。我知道显而易见的答案是添加一个while循环,但是我在实现此策略时遇到了麻烦。我试图寻求帮助,以了解这样做的最佳方法。谢谢。

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

3 个答案:

答案 0 :(得分:1)

我认为您的帖子中的代码缩进不可用,但我想您只是想让用户输入每个循环,在这种情况下,您可以简单地移动代码行

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

答案 1 :(得分:1)

要回答您的原始问题,每次程序循环时都必须重新提示,因此您需要将提示放入循环中。我知道您说您是编码的新手,所以我花了一些时间遍历您的代码并修正/注释了一些内容,希望可以帮助您更高效地完成工作

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

答案 2 :(得分:0)

我有一个非常类似于您所需的代码。 请注意,您没有检查用户的有效输入。

希望有帮助

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