0% found this document useful (0 votes)
17 views

Ch4 - Functions

Uploaded by

Murad Demelash
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Ch4 - Functions

Uploaded by

Murad Demelash
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 12

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(message="How are you?”, name=“James")


Variable scope
Variable scope refers to the accessibility of variables within a
program. In Python, variables can have global or local scope.
E.g. x = 10
def my_func():
y = 5
print(x)
print(y)
my_func()
Default values
Default values allow you to specify a default argument for a
function parameter if no value is provided during the function call.
E.g. def greet(name="Guest"):
print(“Hello”, name)

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.

You might also like