Calling functions
Categories: python language intermediate python
This article looks at different ways to pass in parameters when you call a function. It follows on from the related article on declaring functions.
We will use this simple function for the first part of the tutorial. It has mandatory and optional parameters:
def fancy_print(s, before='[', after=']'):
out = before + s + after
print(out)
Positional parameters
Since the fancy_print
function has one mandatory parameter (s
) and two optional parameters, there are 3 simple ways to call it:
fancy_print('Hello') # Prints '[Hello]'
fancy_print('Hello', '(') # Prints '(Hello]'
fancy_print('Hello', '<', '>') # Prints '<Hello>'
We must supply the first parameter. We can choose to supply the second parameter, or the second and third parameters, because they are optional. If we don't supply a parameter, it takes the default value from the declaration.
The parameters being passed in here are called positional parameters because we use the position of the parameter to identify it. The first parameter is s
, the second is before
, the third is after
.
Named parameters
You can also pass parameters by name. As an example, suppose we wanted to change the after
parameter while leaving the before
parameter set to its default value. We can do this:
fancy_print('Hello', after='>') # Prints '[Hello>'
Although the syntax for named parameters is similar to the syntax for optional parameters, you can mix and match. You could set the value of s
by name:
fancy_print(after='>', s='Hello') # Prints '[Hello>'
Notice that with named parameters, they can be in any order. This can be very useful if you have a function with a lot of parameters. The positional syntax means that you have to remember the parameter order to understand the function call. Using named parameters the calling code is almost self-documenting.
There are some rules about positional and named parameters:
- All the positional parameters must appear before any named parameters.
- Every mandatory parameter must be given a value, which can be by position or name.
- No parameter can be given more than one value. There are two ways this could happen: either the parameter is given a positional value and a named value, or a parameter is named more than once. Neither case is allowed.
Unpacking parameter lists
You can unpack a sequence of values passed into a function, like this:
values = ('<', '>')
fancy_print('hello', *values) # prints <hello>
# Exactly the same as:
fancy_print('hello', '<', '>')
The values
tuple is unpacked and provides 2 parameters to the function.
In 3.4 earlier versions of Python, only one unpacked sequence was permitted, and it had to be immediately after all the positional parameters. As of 3.5, the parameter list can contain a mixture of positional parameters and unpacked sequences, in any order, including multiple unpacked sequences.
You can also unpack a dictionary of named values passed into a function, like this:
dvalues = {'s': 'hello', 'before': '<', 'after': '>'}
fancy_print(**dvalues) # prints <hello>
# Exactly the same as:
fancy_print(s='hello', before='<', after='>')
In 3.4 earlier versions of Python, only one unpacked dictionary was permitted, and it had to be immediately after all the named parameters. As of 3.5, the parameter list can contain a mixture of named parameters and unpacked dictionaries, in any order, including multiple unpacked dictionaries.
As a general rule, all the positional parameters and unpacked sequences should come first, followed by all the named parameters and unpacked dictionaries.
See also
- List comprehensions
- Objects and variables
- Objects and identity
- Immutable objects
- Global variables
- Data types
- Lists vs tuples
- Sequences
- Named tuples
- Operators
- Short circuit evaluation
- Walrus Operator
- For loops
- For loop using range vs iterables
- Changing the loop order
- Using enumerate in a for loop
- Using zip in a for loop
- Looping over multiple items (old article)
- Looping over selected items
- Functions
- Declaring functions
- Function objects and lambdas
- Function decorators
- With statements
- Exception handling
- String functions
- Built-in functions
- Optimisation
- Optimisation good practice
- Low level code optimisation
- Structural optimisation
Join the PythonInformer Newsletter
Sign up using this form to receive an email when new content is added:
Popular tags
2d arrays abstract data type alignment and angle animation arc array arrays bar chart bar style behavioural pattern bezier curve built-in function callable object chain circle classes clipping close closure cmyk colour combinations comparison operator comprehension context context manager conversion count creational pattern data science data types decorator design pattern device space dictionary drawing duck typing efficiency ellipse else encryption enumerate fill filter font font style for loop formula function function composition function plot functools game development generativepy tutorial generator geometry gif global variable gradient greyscale higher order function hsl html image image processing imagesurface immutable object in operator index inner function input installing iter iterable iterator itertools join l system lambda function latex len lerp line line plot line style linear gradient linspace list list comprehension logical operator lru_cache magic method mandelbrot mandelbrot set map marker style matplotlib monad mutability named parameter numeric python numpy object open operator optimisation optional parameter or pandas partial application path pattern permutations pie chart pil pillow polygon pong positional parameter print product programming paradigms programming techniques pure function python standard library radial gradient range recipes rectangle recursion reduce regular polygon repeat rgb rotation roundrect scaling scatter plot scipy sector segment sequence setup shape singleton slice slicing sound spirograph sprite square str stream string stroke structural pattern subpath symmetric encryption template tex text text metrics tinkerbell fractal transform translation transparency triangle truthy value tuple turtle unpacking user space vectorisation webserver website while loop zip zip_longest