Калькулятор Loop в Python 3 - PullRequest
       2

Калькулятор Loop в Python 3

0 голосов
/ 13 февраля 2019

Я новичок в программировании и изо всех сил пытаюсь вернуть свой цикл кода к началу, чтобы пользователь мог выбрать другую операцию, не перезапуская программу.Я знаю, что очевидный ответ - добавить цикл 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 голосов
/ 14 февраля 2019

Чтобы ответить на исходный вопрос, вы должны повторять запрос каждый раз, когда программа зацикливается, поэтому вы хотите поместить подсказку в цикл.Я знаю, что вы говорите, что вы новичок в кодировании, поэтому я потратил время, чтобы просмотреть ваш код и исправить / прокомментировать некоторые вещи, чтобы, надеюсь, помочь вам сделать что-то более эффективное

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()
0 голосов
/ 14 февраля 2019

У меня был код, очень похожий на то, что вам нужно.Обратите внимание, что вы не проверили правильность ввода от пользователя.

надеюсь, это поможет

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()
0 голосов
/ 13 февраля 2019

Я думаю, что в вашем посте отключен отступ кода, но я думаю, что вы просто хотите попросить пользователя ввести каждый цикл, и в этом случае вы можете просто переместить строку кода

while True:
    operator=input('Choose a number 1 - 6: ')
    if operator == '1' or operator == 'Add' or operator == 'add':
..... # all your other code
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...