AITCHISON COLLEGE Topic: Functions in Python
Class: M2
PREP SCHOOL
ICT Department
Objectives
Students will be able to:
• Understand functions in Python
• Defining a function
• Calling a function
• Passing arguments to a function
• Apply functions using examples
Functions in Python
•A function is a block of code that perform specific task.
•Functions only run when it is called.
Examples
• input()
• print()
• append()
Benefits of Functions
•Reusability
•Programs are easier to maintain
•Programs are easier to understand
Defining a Function
•In Python a function is defined using the def keyword:
Examples
Example: 1
def my_function():
print(“Hello World!”)
Example: 2
def cube():
a=int(input(“Enter a number”))
b=a**3
print(b)
return b
Calling a Function
•To call a function, use the function name followed by parenthesis.
Example:
def my_function():
print(“Hello World!”)
Calling function:
my_function()
Output:
>>>Hello World!
Passing Arguments
• Information can be passed into functions as arguments.
• Arguments are specified after the function name, inside the parentheses. You can
add as many arguments as you want, just separate them with a comma.
• The terms parameter and argument can be used for the same thing: information
that are passed into a function.
Example:
def addition(x,y):
print(x+y)
Calling function:
addition(2,3)
Output:
>>> 5
Recap
In this lesson, we have discussed:
• Concept of functions in python
• Creating user defined functions
• Calling a function
• Passing arguments to a function
Thank You