FUNCTIONS IN PYTHON
Group 3
Functions are blocks of code that only execute when they are called
You can pass data, known as parameters, into a function.
A function can return data as a result.
There are Two Types of Functions in Python:
1. Standard Library Functions
2. User Defined Functions
Standard Library Functions
• These are functions that come with Python
• These include : print(), input() and int()
• When using these types of functions the only
requirement is the function name and
appropriate inputs
User Defined Functions
• These are functions that a programmer can create
• They have a Name, Arguments (input parameters) and a Return value
• If the name is more than one word an underscore is used to separate the words.
Also its common to make the function name lower caps
Declaring a Function
The way to declare (create) a function is as follows
def function_name(arguments):
# code goes here
return
def - keyword used to declare a function
function_name - any name given to the function
arguments - any value/parameter that the function will accept
return (optional) - returns value from a function
For example
def adding_numbers(x, y):
total = x + y
return total
This function, when called, will add numbers x and y and return the value called
total
• After declaring a Function the next step is to Call it
• This is done because the function will not be executed unless its Called
def adding_numbers(x,y):
total = x + y
return total
print(adding_numbers(2,5)) #this is call statement
• When calling the function we had to pass (2,5) as arguments
• The number of arguments passed at declaration of the function must equal the
number of arguments passed when the Function is called
EXAMPLES OF FUNCTIONS
#creating a function that greets you personally
name = str(input("What is your name: "))
def whats_your_name():
print("Welcome home %s we have missed you" %name)
whats_your_name()
print("Hope you stay a while")
Output:
What is your name: Taku
Welcome home Taku we have missed you
Hope you stay a while
EXAMPLES OF FUNCTIONS
"""creating a function that checks for temperature and returns a text. The program
terminates if input is zero""“
x = int(input("Enter the temperature: "))
def weather_report(x):
if x < 60:
print("Its too cold")
elif x > 100:
print("Its too hot")
else:
print("its just right")
while x != 0:
print(weather_report(x))
Benefits of Using Functions
1. Code Reusable - We can use the same function
multiple times in our program which makes our
code reusable.
2. Code Readability - Functions help us break
our code into chunks to make our program
readable and easy to understand
3. We can track a large Python program easily
when it is divided into multiple functions.