[英]Positional argument follows keyword argument | Error while calling function
首先,我了解到,在定义函数时,您必须先放置位置参数,然后放置默认参数,以避免解释程序出现歧义。 这就是为什么当我们尝试这样做时会引发错误。
例如,在以下代码中,a和b不能在运行时求值,因为它会引发错误
def func(a=1,b):
return a+b
func(2)
( Error:non-default argument follows default argument
)
这是可以理解的。
但是,为什么以下导致错误。 它不是在定义函数时发生的,而是在调用函数时发生的。
def student(firstname, standard,lastname):
print(firstname, lastname, 'studies in', standard, 'Standard')
student(firstname ='John','Gates','Seventh')
Error:positional argument follows keyword argument
我们不能同时传递带有关键字和不带有关键字的参数吗? [编辑]:问题不是可能的重复项,因为重复项讨论了定义默认参数的情况。 我还没有定义它们。 我只是问为什么我们不能混合使用关键字值参数和直接值参数。
正如错误所言:
Error:positional argument follows keyword argument
关键字参数后不能有位置参数。
您的示例就是一个很好的例子。
您将第一个参数指定为关键字参数。 因此,现在解释器如何解释参数顺序是不明确的。 第二个参数是否成为第一个参数? 第二个参数? 但是您已经指定了第一个参数( firstname='John'
),那么位置参数会发生什么?
def学生(名字,标准,姓氏):打印(名字,姓氏,“学习”,标准,“标准”)
student(firstname ='John','Gates','Seventh')
解释是否解释为:
student(firstname ='John',standard='Gates',lastname='Seventh')
要么
student(firstname ='John',standard='Gates',lastname='Seventh')
要么
student(firstname ='John',firstname='Gates',lastname='Seventh')
关于什么:
student(lastname ='John','Gates','Seventh')
这个?
student(lastname ='John',firstname='Gates',standard='Seventh')
或这个?
student(lastname ='John',standard='Gates',firstname='Seventh')
尝试调试与参数匹配的参数的好运。
也许您应该尝试:
student('John', 'Gates', 'Stevehn')
我不知道您是否可以在调用函数的同时定义变量。
悉尼
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.