【问题标题】:Function call missing required positional argument:函数调用缺少必需的位置参数:
【发布时间】:2018-10-12 02:58:06
【问题描述】:

我正在为课堂制作一个餐厅标签程序,老师要求我们从原始版本“模块化”它。但是,我不断收到错误”

TypeError:computeTotal() 缺少 1 个必需的位置参数:'drinks')

我知道这是一个范围错误,但我不确定如何修复它,因为该变量是一个全局变量。

def getdrinks():
    drinks = float(input('dollar amount for drinks: $'))
    return drinks

def getapps():
    apps = float(input('dollar amount for apps: $'))
    return apps

def getMC():
    mainCourse = float(input('dollar amount for main course: $'))
    return mainCourse

def getdessert():
    dessert = float(input('dollar amount for desserts: $'))
    return dessert

def getPurchaseAmts():
    getdrinks()
    getapps()
    getMC()
    getdessert()
getPurchaseAmts()

def computeTotal(drinks, apps, mainCourse, dessert):
    Total = (drinks + apps + mainCourse + dessert)
    print ("Bill total (before tax and preTip): ",Total)
computeTotal()    

drinks = getdrinks()
apps = getapps()
mainCourse = getMC()
dessert = getdessert()

【问题讨论】:

  • 请不要发布代码图片(或者,更糟糕的是,图片链接)。 edit 问题并将代码复制并粘贴到其中。另外,标记一种语言:python.
  • 我已经改了,对不起。
  • 你为你的方法def computeTotal定义了多少参数?你给了多少computeTotal()?现在,请再次阅读您的错误。而且和作用域无关

标签: python python-3.x variables scope


【解决方案1】:

您将参数与外部定义的值混淆了。

这些参数可以被命名为完全不同的东西,即使它们当前与其他参数相同,但这并不意味着它们的值会自动传递给函数

例如,

def computeTotal(a, b, c, d):
    total = (a + b + c + d)
    print ("Bill total (before tax and preTip): ",total)


drinks = getdrinks()
apps = getapps()
mainCourse = getMC()
dessert = getdessert()

# this must be last, and you need to pass values into the function 
computeTotal(drinks, apps, mainCourse, dessert)

你可以删除getPurchaseAmts(),因为它没有做任何事情,只是让你重复输入两次

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-07
    • 1970-01-01
    • 2015-03-16
    • 1970-01-01
    • 2022-11-13
    • 2023-04-01
    • 1970-01-01
    相关资源
    最近更新 更多