positional-keyword
Functions can take two different kinds of arguments. A positional argument is just the object itself. A keyword argument is a name assigned to an object.
Example
>>> print('Hello', 'world!', sep=', ')
Hello, world!
The first two strings 'Hello' and world!' are positional arguments.
The sep=', ' is a keyword argument.
Note A keyword argument can be passed positionally in some cases.
def sum(a, b=1):
return a + b
sum(1, b=5)
sum(1, 5) # same as above
Somtimes this is forced, in the case of the pow() function.
The reverse is also true:
>>> def foo(a, b):
... print(a, b)
...
>>> foo(a=1, b=2)
1 2
>>> foo(b=1, a=2)
2 1
More info
• Keyword only arguments
• Positional only arguments
• /tag param-arg (Parameters vs. Arguments)
return
•
• A function will return
• When you want to print a value from a function, it's best to return the value and print the function call instead, like
A value created inside a function can't be used outside of it unless you return it.
Consider the following function:
def square(n):
return n * n
If we wanted to store 5 squared in a variable called x, we would do:
x = square(5). x would now equal 25.
Common Mistakes
>>> def square(n):
... n * n # calculates then throws away, returns None
...
>>> x = square(5)
>>> print(x)
None
>>> def square(n):
... print(n * n) # calculates and prints, then throws away and returns None
...
>>> x = square(5)
25
>>> print(x)
None
Things to note•
print() and return do not accomplish the same thing. print() will show the value, and then it will be gone.• A function will return
None if it ends without a return statement.• When you want to print a value from a function, it's best to return the value and print the function call instead, like
print(square(5)).