What are functions?

Functions in Python are named blocks of code that are used in large programs to separate code into manageable chunks. They are usually used when you need to perform the same task multiple times throughout the program.

To define a function, the def keyword is used. For example, to create a function called my_first_function, the following code would be used:

def my_first_function():

Any indented line of code after the function definition will be the part of the function:

def my_first_function():
    print('Hello World!')

If we run the program now, nothing will be printed out. This is because the functions need to be called. When you call a function, you are instructing Python to execute the code in it. It is done like this:

my_first_function()

>>> 
Hello World!
>>>
When you call a function, do not type the colon after the parentheses. Also, make sure to call the function after its definition – if you call the function before its defined, Python will report an error.

 

I can call this function multiple times:

my_first_function()
my_first_function()
my_first_function()

The output:

>>>
Hello World!
Hello World!
Hello World!
>>>

The parentheses after the function name are used to provide extra information to a function. Consider the following function, used to convert Euro to USD:

def usd_to_euro(dollars):
    conversion = dollars * 0.80
    print(dollars, 'USD equals', conversion, 'Euro.')


usd_to_euro(150)

The output:

>>>
150 USD equals 120.0 Euro.
>>>

We’ve defined the usd_to_euro function with a parameter inside the parentheses. A parameter is simply a variable that will be assigned a value when a function is called. So in our case, when we call the function, we also needed to pass the value (the amount of dollars we would like to convert). The value that we are passing (e.g. 150) is called an argument. So when we call the function. the argument will be passed to the usd_to_euro() function, and that value will be stored in the dollars variable. This variable will then be used to make the conversion.

We can call the same function multiple times with different arguments:

usd_to_euro(150)
usd_to_euro(30)
usd_to_euro(4000)

The output:

>>>
150 USD equals 120.0 Euro.
30 USD equals 24.0 Euro.
4000 USD equals 3200.0 Euro.
>>>
Geek University 2022