Reputation: 511
First, I understand that while defining function you have to place positional arguments first and then default arguments to avoid the ambiguity situation for interpreter. That is why when we try to do it, it throws an error.
For e.g. in the following code, a and b cannot be evaluated at the runtime due to which it throws an error
def func(a=1,b):
return a+b
func(2)
(Error:non-default argument follows default argument
)
This is understandable.
But why does the following results in an error. It does not occur at the time of defining function but at the time of calling function.
def student(firstname, standard,lastname):
print(firstname, lastname, 'studies in', standard, 'Standard')
student(firstname ='John','Gates','Seventh')
Error:positional argument follows keyword argument
Can't we pass parameters with and without keywords simultaneously? [Edit]: The question is not a possible duplicates as the duplicates talk about the case when default arguments are defines. I've not defined them. I am just asking why can't we mix keyword value parameters and direct value parameters.
Upvotes: 0
Views: 1522
Reputation: 2144
It's exactly as the error says:
Error:positional argument follows keyword argument
You can't have positional arguments following keyword arguments.
Your example is a good case in point.
You specify the first argument as a keyword argument. So it's ambiguous how the interpreter is to interpret the order of parameters now. Does the 2nd argument become the first parameter? The second parameter? But you've already specified the first parameter (firstname='John'
) so what happens to the positional parameter?
def student(firstname, standard,lastname): print(firstname, lastname, 'studies in', standard, 'Standard')
student(firstname ='John','Gates','Seventh')
Does the interpret interpret this as:
student(firstname ='John',standard='Gates',lastname='Seventh')
or
student(firstname ='John',standard='Gates',lastname='Seventh')
or
student(firstname ='John',firstname='Gates',lastname='Seventh')
What about:
student(lastname ='John','Gates','Seventh')
This?
student(lastname ='John',firstname='Gates',standard='Seventh')
or this?
student(lastname ='John',standard='Gates',firstname='Seventh')
Good luck trying to debug what argument matches what parameter.
Upvotes: 1
Reputation: 3
Maybe You should try :
student('John', 'Gates', 'Stevehn')
I dont know if you can define a variable in same time as calling a function.
Sydney
Upvotes: 0