【问题标题】:Function: multiple arguments功能:多个参数
【发布时间】:2021-10-05 18:02:51
【问题描述】:

我是 python 新手,我目前在当地大学就读于初学者 python。这是我的 ICS 学位的要求。昨天我有一个测验,问题是“以下什么是参数。我知道 def register_for_class(studen_id, crn): 是参数,我知道函数调用是参数,但还有什么被认为是参数?我的老师不会告诉我的。她只是说不止函数调用作为参数。

def register_for_class(student_id, crn): # parameter
    add_class(student_id, crn, 2022, 'Spring')
    student_name = get_name(student_id)
    class_name = get_class(crn)
    msg = student_name + ' is now enrolled in: ' + class_name
    return msg

register_for_class(19283746, 22319) # function call 

【问题讨论】:

  • 在我看来参数和参数是同义词。您示例中的参数/参数是 19283746 和 22319
  • 您对老师的回答是正确的。我的意思是,即使是文档也使用 parameters/arguments 可互换,"The actual parameters (arguments) to a function call are introduced in the local symbol table of the called function when it is called" - 比必要的更详细一点,但它使函数 callarguments 传递给函数定义以将它们与parameters 的定义相匹配。
  • 另外,(作为记忆辅助)我认为术语的命名有助于通过传递他们的“参数”来调用函数定义的“争论”,然后函数定义有参数必须与完全匹配正确对齐和匹配,否则函数调用将“失败”返回“错误消息”。
  • 我给我的老师发了电子邮件,解释了参数和参数,她不会给我一个直接的答案。她从来不这样做,这令人气愤。这是她的回应。 ” “你说得对! def register_for_class (student_id, crn): # 这不是参数吗? register_for_class(19283746, 22319) # 这不是要通过参数传递的参数吗?但是,请查看其余代码以查找您可能遗漏的任何内容。""
  • 除了下面的出色答案之外,您还可以查看Mozilla docs,其中对差异进行了很好的解释,可能有助于您更好地理解。

标签: python function arguments new-operator


【解决方案1】:

参数是出现在函数定义中的变量名称,因此在您的示例中:

def register_for_class(student_id, crn):

student_idcrn 是参数。

参数是你在调用函数时传递给函数的值,所以当你调用时:

register_for_class(19283746, 22319)

1928374622319 是参数。

register_for_class 函数定义中还有几个函数调用,所以如果你的老师说有更多参数,她可能是指那些。例如:

add_class(student_id, crn, 2022, 'Spring') # four arguments passed here

注意 1: 变量既可以是参数也可以是自变量(例如,上面的 student_id)。

注意 2: 许多人交替使用术语 parameterargument。我上面给出的定义在技术上是正确的,但你应该知道,大多数人在谈话中不会区分这两者。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-26
    • 2017-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多