Introduction to Functions in Python
Functions are reusable blocks of code that perform specific tasks. In this lesson, you will learn how to define simple functions and how to use them.
Let's jump right in and create and use our first function.
def log_message():
print('Hello World')
log_message()
We've created a function called log_message that logs the message 'Hello, world'
. Then, we've called the our function.
Let's take a look at how this works.
In Python, you define a function using the def
keyword, followed by the function name, parentheses, and a colon. The function body is then indented below.
def name():
# function body
print('Hi')
After defining a function, we can call it using its name followed by a pair of parentheses.
# call the function
name()
The function body is only executed when the function is being called, which is why, in the following example, the updated value of num is printed:
num = 0
def log_message():
print(num)
num = 1
log_message()
Why all this, you may ask? One reason is that you can call a function as often as you want. Let's try it:
def log_message():
print('Hello World')
log_message()
log_message()
This saves you from having to copy and paste the code each time you want to perform a task.
Functions allow you to encapsulate specific tasks into smaller, more manageable pieces, making it easier to understand and work with your code.
What will be the output?
def func():
print(2)
func()
What will be the output?
price = 1
def func():
print(price)
func()
What will be the output?
price = 1
def func():
print(price)
num = 2
What will be the output?
price = 1
def func():
print(price)
price = 2
func()
Another important aspect of functions is their ability to return values. You can achieve this by using the return
keyword.
The value specified after the return
keyword is passed back to the caller of the function and can then be used for further operations:
def func():
return 5
result = func()
print(result)
Note that if a return
statement is encountered, the function immediately exits.
Here, the print()
function that follows the return
statement is not executed:
def func():
return 5
print('I am not printed!')
print(func())
You can use this approach to exit a function early if a certain condition is met. For example:
def func():
if True:
return 2
return 5
print(func())
What will be the output?
def func():
return 10
print(func())
What will be the output?
def func():
return 10
return 2
print(func())
What will be the output?
def func():
if False:
return 10
return 2
print(func())