top of page
Search
Writer's pictureMaia

Python Tips Series: Function Arguments



In every Python project, we always use at least one function, even with the simplest program in the world: Hello World!. We use 'print()' function as below.

When I was just beginning learning Python, I always confused about function arguments. For example, how can a function like 'print()' can accept any number of parameters as below.

Actually, to write a function with arbitrary number of arguments like that is very easy. It's called unpacking parameters.

Let's create a simple function that perform mathematical addition with dynamic number of arguments.

Theoretically, there are two types of function arguments: positional arguments and keyword arguments.

In the sample code below, we define a simple 'add()' function that takes exactly two parameters.

This function requires exactly two params and the order of params is important. If we try to call the function with different numbers of params we will get error.

However, we can define some default values for function arguments. The rule is the params that has default values have to be at the end of the list.

We can also pass params to a function using keyword or name/value pair as below.

But we need to follow the rule that if we start using keyword param, then all params after it must be keyword params too. We can use positional params after keyword params or it will errors.


That's all the basic but very important things to know about Python function arguments. Hope it helps.


Happy Coding!



Recent Posts

See All

Comments


Post: Blog2_Post
bottom of page