首页 > 解决方案 > 带有函数和列表的 Python 计算器脚本

问题描述

我正在尝试创建一个简单的 python 计算器,其输入为列表和定义可以执行的操作的函数。

我无法让我的函数在它们返回后返回值。

该程序应该以列表的形式获取数字,然后将它们传递到程序主体的 while 循环中。用户可以在程序退出之前执行任意数量的操作。

请让我知道我的错误是什么,或者我是否需要添加任何内容。

def display_menu():
    print("Please Choose an option")
    print("1. Add (+)")
    print("2. Subtract (-)")
    print("3. Multiply (*)")
    print("4. Divide (/)")
    print("q to quit")

def addition():
    numlist = input("please enter at least 2 numbers to be operated on.").split()
    numlist = [float(num) for num in numlist]
    num1 = numlist[0]
    del numlist[0]
    for num in numlist:
        num1 = num1 + num
    return num1   

def subtraction():  
    numlist = input("please enter at least 2 numbers to be operated on.").split()
    numlist = [float(num) for num in numlist]
    num1 = numlist[0]
    del numlist[0]
    for num in numlist:
        num1 = num1 - num
    return num1

def multiply():   
    numlist = input("please enter at least 2 numbers to be operated on.").split()
    numlist = [float(num) for num in numlist]
    num1 = numlist[0]
    del numlist[0]
    for num in numlist:
        num1 = num1 * num
    return num1

def division():   
    numlist = input("please enter at least 2 numbers to be operated on.").split()
    numlist = [float(num) for num in numlist]
    num1 = numlist[0]
    del numlist[0]
    for num in numlist:
        num1 = num1 * num
    return num1

displ_menu()

operator = input("Please enter an operator: ")

while operator != "q":

    if operator == "+":
        addition()
    elif operator == "-":
        subtraction()
    elif operator == "*":
        multiply()
    else:
        division()
    displ_menu()
    operator = input("please enter an operator")    
print("Closing calculator")

标签: pythonlistfunctionloops

解决方案


推荐阅读