【发布时间】:2020-06-15 21:38:01
【问题描述】:
我刚开始学习python,在一些关于我为了练习而做的函数的练习中,我提出了以下简单的想法,我想稍后以更大的方式进行测试,这是我的代码:
def test_function(firstn):
firstn = input("introduce your name: ") ## assigns the value of the introduced value
print(firstn + " Perez") ##prints the function + the surname
test_function(0) ## calls the function and executes
一切都按预期工作,问题是,当我第一次完成最后一行的代码时,我调用了函数“test_function”,如果我未指定括号之间的值,代码失败并出现以下错误留言:
def test_function(firstn):
firstn = input("introduce your name: ")
print(firstn + " Perez")
test_function() ## without any value
"TypeError: test_function() missing 1 required positional argument: 'firstn'"
我的问题是,为什么当我用括号之间的任何随机数调用函数时它可以工作,而当我只调用没有任何值的函数时它不起作用?
感谢您提供的任何反馈或任何建议,以改进我的使用。
【问题讨论】:
-
def test_function(firstn)定义了一个采用 1 个必需参数的函数。您实际上并没有使用该名称,实际上您将其重新绑定到不同的值。可能您只是想def test_function()定义一个没有输入参数的函数。 -
参见 Python 教程中的Defining Functions。