Question
Asked By – q0987
Based on this
A positional argument is a name that is not followed by an equal sign
(=) and default value.A keyword argument is followed by an equal sign and an expression that
gives its default value.
def rectangleArea(width, height):
return width * height
print rectangleArea(width=1, height=2)
Question. I assume that both width
and height
are positional arguments. Then why can we also call it with the keyword argument syntax?
Now we will see solution for issue: Positional argument vs keyword argument
Answer
That text you quote seems to be confused about two totally different things:
- Positional and keyword arguments are a feature of calls to a function (see Python reference section
5.3.4 Calls
). - Default values are a feature of function definitions, as per section
7.6 Function definitions
I suspect the people who put together that course-ware weren’t totally familiar with Python 🙂 Hence that link you provide is not a very good quality one.
In your call to your function, you’re using the “keyword argument” feature (where the argument is named rather than relying on its position). Without that, values are bound to names based on order alone. So, in this example, the two calls below are equivalent:
def process_a_and_b(a, b):
blah_blah_blah()
process_a_and_b(1, 2)
process_a_and_b(b=2, a=1)
By further way of example, refer to the following definition and calls:
def fn(a, b, c=1): # a/b required, c optional.
return a * b + c
print(fn(1, 2)) # returns 3, positional and default.
print(fn(1, 2, 3)) # returns 5, positional.
print(fn(c=5, b=2, a=2)) # returns 9, named.
print(fn(b=2, a=2)) # returns 5, named and default.
print(fn(5, c=2, b=1)) # returns 7, positional and named.
print(fn(8, b=0)) # returns 1, positional, named and default.
This question is answered By – paxdiablo
This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0