首页 > 解决方案 > 清除输出结果并重用结果

问题描述

我正在创建一个计算器,我希望能够询问用户是否要清除结果或使用第二个数字重用结果来创建新结果。任何提示或帮助表示赞赏

def cally():
    op = input('''Please type in the math operation you would like to complete:
+ for addition
- for subtraction
* for multiplication
/ for division
''')

    n1 = float(input('Please enter the first number: '))
    n2 = float(input('Please enter the second number: '))

    if op == '+':
        print(n1 + n2)

    elif op == '-':
        print(n1 - n2)

    elif op == '*':
        print(n1 * n2)
    elif op == '/':
        print(n1 / n2)

    else:
        print('You have not typed a valid operator')
cally()

def again():


    calc_again = input("Do you want to calculate again?Please type Y for YES or N for NO.")

    if calc_again == 'Y':
        cally()

    elif calc_again == 'N':
        print('See you later.')

    else:
        again()
cally()

标签: python

解决方案


修改cally()以添加一个可选参数,该参数是先前的结果。如果存在此参数,请将其用作n1而不是提示。打印后也返回当前结果。

然后,在您调用 之后cally(),将其结果保存在一个变量中,如果用户说他们想重用最后一个结果,则将相同的变量传递回对 的下一次调用cally()


推荐阅读