Skip to content

Functions#

Just like in Bash, you can define functions in Python and they're used in the same way and for the same reasons. And defining one is equally as simple:

1
2
3
4
5
6
7
8
>>> def hello_world(): print("Hello, world!")
...

>>> hello_world
<function hello_world at 0x000001F07B7D9310>

>>> hello_world()
Hello, world!

Note

When defining the function in the terminal, I had to press Enter twice.

When using just the name of the function, without the (), then we can see we just have a reference to a function - <function hello_world at 0x000001F07B7D9310> - which means we have a function at memory address 0x000001F07B7D9310 (in RAM.)

When we use the (), we call the function referenced at 0x000001F07B7D9310, and its body is executed.

Functions can, of course, have parameters too, even optional ones!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
>>> def hello_person(person): print(f"Hello, {person}")
...

>>> hello_person("Mike")
Hello, Mike

>>> hello_person()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: hello_person() missing 1 required positional argument: 'person'

The person parameter is required. It cannot be omitted, as we can see in the last call to the function. But what if we want to make it optional? Well, we just need to provide a default value:

1
2
3
4
>>> def hello_person(person="world"): print(f"Hello, {person}")
...
>>> hello_person()
Hello, world

And that's it.

We can also return values from functions too, as you might have suspected:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
>>> def hello_person(person="world"): return f"Hello, {person}"
...

>>> hello_person()
'Hello, world'

>>> msg = hello_person()
>>> msg
'Hello, world'

>>> msg = hello_person("Mike")
>>> msg
'Hello, Mike'

And at this point, that's all you need to know.