Ch4 - Functions
Ch4 - Functions
Chapter 4
Functions
Functions are blocks of organized, reusable code that perform a
specific task. They provide modularity and abstraction, making
code more readable, maintainable, and easier to debug.
Benefits of using functions
• Encapsulation: Grouping related code together.
• Reusability: Functions can be reused in different parts of the
program.
• Modularity: Breaking down complex tasks into smaller,
manageable components.
• Abstraction: Hiding implementation details and focusing on the
functionality.
• Maintainability: Easier to debug and update code.
Defining functions
Functions in Python are defined using the def keyword followed
by the function name and a set of parentheses containing
optional parameters. The body of the function is indented.
E.g. def greet():
print("Hello, world!")
greet()
Passing arguments and returning values
Functions can accept input values called arguments and can also
return output values.
E.g. def add(a, b):
return a + b
result = add(3, 5)
print(result)
Keyword arguments
Keyword arguments allow you to pass arguments to a function
by specifying the parameter name along with the value.
E.g. def greet(name, message):
print(“Hello“, name, message)
greet()
greet(“James")
Recursive functions
A recursive function is a function that calls itself during its execution. It allows
solving problems by breaking them down into smaller, similar subproblems.
E.g. def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
result = factorial(5)
print(result)
Functions example 1
Write a python function that takes in a number as input and
calculates and returns the square of the number.
Functions example 2
Write a python function that takes in a base and an exponent as
input and returns the base to the power of the exponent.
Functions example 3
Write a python function that takes a number as input and checks
if it’s a perfect number.