Introduction to Python
Python functions
Summary Notes
2
Contents
3 Lesson objectives
3 What are Python functions?
3 Why use Python functions?
3 Function syntax
3 Function example
4 Source code
INTRODUCTION TO PYTHON
3
Lesson objectives
By the end of this lesson, you should be able to:
• Define Python functions
• Demonstrate the use of functions
What are Python functions?
A Python function is a block of statements that performs some task and sometimes returns data for further
computation. The goal is to put some commonly or repeatedly done tasks together and create a function to avoid
writing the same block of code over and over again for different inputs, we can do the function calls to reuse a block
of code contained in it over and over again.
Why use Python functions?
There are various reasons why programmers use functions, this includes the following:
• Code decomposition
• Reusability
• Extensibility
Function syntax
Function example
INTRODUCTION TO PYTHON
4
Source code
[Link]
# Greeting function
def greeting(name):
print("Hello " + name + " how are you doing?")
greeting("Alexis")
# calculating the area of a rectangle function
def calculate_area_rect(length, width):
area = length * width
print(area)
calculate_area_rect(2, 5)
# withdraw money function
def withdraw_money(amount):
balance = 1000
current_balance = balance - amount
return current_balance
print("After your withdrawal, you have $" + str(withdraw_money(600)) + " remaining")
INTRODUCTION TO PYTHON