Python 如何更好地实现用户操作的历史记录?

Python 如何更好地实现用户操作的历史记录?,python,Python,我决定做一个计算器作为一个项目。 实现基本的加法、减法、除法和乘法相当容易 我想添加更多功能,所以我决定在用户视图中实现一个结果列表。然而,我很难从数字上跟踪结果。我编写了一个由if语句组成的迷宫,这些语句功能强大,但代码似乎过于繁杂。我相信有更好的方法来处理这个问题 有什么建议吗 def add(x, y): return x + y def sub(x, y): return x - y def mul(x, y): return x * y def di

我决定做一个计算器作为一个项目。 实现基本的加法、减法、除法和乘法相当容易

我想添加更多功能,所以我决定在用户视图中实现一个结果列表。然而,我很难从数字上跟踪结果。我编写了一个由if语句组成的迷宫,这些语句功能强大,但代码似乎过于繁杂。我相信有更好的方法来处理这个问题

有什么建议吗

def add(x, y):
    return x + y


def sub(x, y):
    return x - y


def mul(x, y):
    return x * y


def div(x, y):
    value = None
    while True:
        try:
            value = x / y
            break
        except ZeroDivisionError:
            print('Value is not dividable by 0, try again')
            break
    return value


def num_input(prompt='Enter a number: '):
    while True:
        try:
            print(prompt, end='')
            x = int(input())
            break
        except ValueError:
            print('You must input a number. Try again.')
    return x


def get_two_val():
    x, y = num_input(), num_input()
    return x, y


print("Welcome to Simple Calc")

# declaration of variables
num_of_calc_counter = 0
index_of_calc = 1
calculations = []

while True:

    print("Choose from the following options:")
    print(" 1. Add")
    print(" 2. Subtract")
    print(" 3. Multiply")
    print(" 4. Divide")
    print(" 5. Sales Tax Calculator")
    print(" 6. Recent Calculations")
    print(" 0. Quit")

    usrChoice = num_input('Enter your choice: ')

    '''
    Menu workflow
        options 1-4 take in two numbers and perform the specified calculation and
        then add the result to a master list that the user can reference later.
        lastly, the workflow increments the num_of_calc variable by 1 for recent
        calc logic

        option 5 is a simple tax calculator that needs work or option to enter
        or find tax rate

        option 6 returns a list of all the calculations perform by the user
    '''
    if usrChoice is 1:
        numbers = get_two_val()
        result = add(*numbers)
        print(numbers[0], "plus", numbers[1], "equals", result)
        calculations.extend([result])
        num_of_calc_counter += 1

    elif usrChoice is 2:
        numbers = get_two_val()
        result = sub(*numbers)
        print(numbers[0], "minus", numbers[1], "equals", result)
        calculations.extend([result])
        num_of_calc_counter += 1

    elif usrChoice is 3:
        numbers = get_two_val()
        result = mul(*numbers)
        print(numbers[0], "times", numbers[1], "equals", result)
        calculations.extend([result])
        num_of_calc_counter += 1

    elif usrChoice is 4:
        numbers = get_two_val()
        result = div(*numbers)
        print(numbers[0], "divided by", numbers[1], "equals", result)
        calculations.extend([result])
        num_of_calc_counter += 1

    elif usrChoice is 5:
        tax_rate = .0875
        price = float(input("What is the price?: "))
        total_tax = tax_rate * price
        final_amount = total_tax + price
        print('Tax rate: ', tax_rate, '%')
        print('Sales tax: $', total_tax)
        print('_____________________________')
        print('Final amount: $', final_amount)
    #
    elif usrChoice is 6:
        if len(calculations) is 0:
            print('There are no calculations')
        elif num_of_calc_counter == 0:
            index_of_calc = 1
            for i in calculations:
                print(index_of_calc, i)
                index_of_calc += 1
            num_of_calc_counter += 1
        elif index_of_calc == num_of_calc_counter:
            index_of_calc = 1
            for i in calculations:
                print(index_of_calc, i)
                index_of_calc += 1
            num_of_calc_counter += 1
        elif num_of_calc_counter > index_of_calc:
            index_of_calc = 1
            for i in calculations:
                print(index_of_calc, i)
                index_of_calc += 1
            num_of_calc_counter -= 1
        elif num_of_calc_counter < index_of_calc:
            index_of_calc = 1
            for i in calculations:
                print(index_of_calc, i)
                index_of_calc += 1
            num_of_calc_counter += 1

    elif usrChoice is 0:
        break

我不知道你是否能找到更简单的方法:

def num_input(prompt='Enter a number: '):
    finished = False
    while not finished:
        string_input = input(prompt)
        try:
            input_translated = int(string_input)
        except ValueError:
            print('You must input a number. Try again.')
        else:
            finished = True
    return input_translated

def division_operation(x, y):
    if y == 0:
        print('Value is not dividable by 0, try again')
        return None
    else:
        return x / y

math_operations_values = [
    (lambda x, y: x + y, 'plus'),
    (lambda x, y: x - y, 'minus'),
    (lambda x, y: x * y, 'times'),
    (division_operation, 'divided by')
    ]

def get_two_val():
    return (num_input(), num_input())

def operate_on_numbers(operation_index):
    def operate():
        numbers = get_two_val()
        operator, operation_string = math_operations_values[operation_index]
        result = operator(*numbers)
        if result is not None:
            print(numbers[0], operation_string, numbers[1], "equals", result)
            calculations.append(result)

    return operate

def tax_computation():
    tax_rate = .0875
    price = float(input("What is the price?: "))
    total_tax = tax_rate * price
    final_amount = total_tax + price
    print('Tax rate: ', tax_rate * 100, '%')
    print('Sales tax: $', total_tax)
    print('_____________________________')
    print('Final amount: $', final_amount)

def show_computations():
    if calculations:
        for (index, values) in enumerate(calculations, start=1):
            print(f'{index}: {values}')
    else:
        print('There are no calculations')

calculations = []
finished = False

choices_actions = [
    operate_on_numbers(0),
    operate_on_numbers(1),
    operate_on_numbers(2),
    operate_on_numbers(3),
    tax_computation,
    show_computations
    ]

while not finished:

    print("""

Choose from the following options:
1. Add
2. Subtract
3. Multiply
4. Divide
5. Sales Tax Calculator
6. Recent Calculations
0. Quit""")

    user_choice = num_input('Enter your choice: ')

    '''
    Menu workflow
        options 1-4 take in two numbers and perform the specified calculation and
        then add the result to a master list that the user can reference later.
        lastly, the workflow increments the num_of_calc variable by 1 for recent
        calc logic

        option 5 is a simple tax calculator that needs work or option to enter
        or find tax rate

        option 6 returns a list of all the calculations perform by the user
    '''

    if user_choice == 0:
        finished = True
    else:
        try:
            operation_to_do = choices_actions[user_choice - 1]
        except IndexError:
            print('Please enter one of choice shown.')
        else:
            operation_to_do()

最后一组if语句的所有主体都是相同的,所以我不知道为什么会有ifs。当你有工作代码并询问良好的代码实践等问题时,你应该将其发布到