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

Week 4-5 Functions and Modular Programming

Uploaded by

do.ebrarr
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

Week 4-5 Functions and Modular Programming

Uploaded by

do.ebrarr
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 14

CENG103 - COMPUTER PROGRAMMING

Functions and Modular


Programming in Python

26 SEPTEMBER 2024
PREPARED BY BÜLENT
HERDEM
Introduction
What are Functions?
 Functions are reusable blocks of code designed to perform a specific task.
 They help to break down complex problems into smaller, manageable parts.

What is Modular Programming?


 Modular programming is the process of dividing a program into separate, self-contained units (modules).
 It promotes clean and organized code, making debugging and updating easier.

Why are These Concepts Important?


Abstraction:
Simplify complex tasks by hiding unnecessary details.
Reusability:
Write code once and reuse it multiple times, reducing redundancy.
Maintainability:
Easier to manage and update programs.
Collaboration:
Modular code enables multiple people to work on different parts of a project.

Real-World Examples
Using predefined functions like print(), len(), or modules like math.Large applications such as web
servers or operating systems are built with modular programming.
Why Use Functions?
 Code Organization: Functions help divide code into meaningful sections, making the program easier to understand
and manage.

 Avoid Repetition: Functions prevent code duplication by allowing you to reuse the same block of code multiple
times with different inputs.

 Easier Debugging: Debugging and testing are simplified because errors can be isolated and fixed in specific
functions without affecting the entire program.

 Improves Collaboration: In larger projects, different team members can work on separate functions, making
collaboration smoother and more efficient.

 Modularity: Breaking a program into functions promotes modular design, making it easier to maintain and update
specific parts of the codebase without affecting other parts.

 Code Readability: Using well-named functions improves the readability of the code, making it more intuitive for
others (and yourself) to understand what the code is doing.

 Abstraction: Functions allow you to hide complex logic and expose only what is necessary, making the codebase
more abstract and easier to work with at a higher level.

 Scalability: With well-structured functions, it's easier to scale your program and add new features without rewriting
large parts of the code.
Function Basics
Defining Functions
Keywords and Syntax
def function_name(parameters):
return String, Number or Boolean etc. #You do not have to use return

Example -1 Calling the function greet: Output

def greet(name): Hello, Alice!


Print( greet("Alice") )
return f"Hello,
{name}!"

Example -2 Calling the function add: Output

def add(a, b): Sum: 9


print( f"Sum:
return a + b
{ add(5,4) }" ))
Scope (Local vs Global Variables)
 Local variables (only inside functions)
 Global variables (accessible anywhere in the program)

Example -1 Example -2

# Global variable
x = 10 # global variable
message = "Hello from the global scope! "
def foo():
def greet():
x = 5 # local variable
global message # Referencing the global variable inside the
print(x) # Output: 5
function
message = "Hello from the local scope!"
print(x) # Output: 10 print("Inside the function:", message)
foo()
print("Before function call:", message)
greet()
print("After function call:", message)
MODULAR PROGRAMMING

Advantages of Modular Programming

 Organizes code: Grouping all operations in a single module makes the code
cleaner and more organized.

 Reusable: You can reuse the functions in the module across different projects.

 Easier to debug: Each function performs a specific task, so if there’s a problem,


you only need to check the related function.

 Facilitates teamwork: Different developers can work on separate modules.


MODULES, CLASSES, FUNCTIONS
Module-1 MODULE-2
Class-1 Class-2 Class-1 Class-2
Function-1

Function-2

..
..
..
Function-n
MODULES, CLASSES, FUNCTIONS
Module – Think of a module as a bakery

Class – Within the bakery, you have different teams that specialize in different types of tasks.

 Bread Team Tasks: (Class-1)  Cookie Team Tasks: (Class-3)


Function-1: Kneading dough, Function-1: Mixing cookie
Function-2: Proofing, dough,
Function-3: Baking Function-2: Portioning,
Function-4: Slicing bread. Function-3: Baking,
Function-4: Decorating cookies.
 Pastry Team Tasks: (Class-2)  Management Team Tasks: (Class-
Function-1: Rolling dough, 4)
Function-2: Shaping pastries, Function-1: Overseeing
Function-3: Filling them with cream or fruit, operations,
Function-4: Baking Function-2: Planning,
Function-3: Team coordination,
Class Activity
# calculator.py # main.py
def add(a, b):
import calculator
"""Adds two numbers."""
# NOTE : docstrings explains the function, class or module
return a + b # Try these codes seperately
# Explore what happens after
def subtract(a, b): # running the codes
"""Subtracts second number from first."""
return a - b # Corrected subtraction operator Try-1> calculator.Add (3,5)

def multiply(a, b): Try-2> calculator.add(3,5)


"""Multiplies two numbers."""
return a * b Try-3> print(calculator.add(3,5) )

def divide(a, b): Try-4> print( f" Total: { calculator.add(3,5) } " )


"""Divides first number by second. Handles division by
zero.""" Try-5> total = calculator.add(3,5)
if b == 0: print (total)
return "Error! Division by zero."
return a / b Try-6>
formula = calculator.subtract(calculator.add(3,5),
divide(4,2) )
print (formula)
What is Recursion?

Recursion is a programming technique where a function calls itself directly or indirectly to solve a
problem. The function typically works by breaking down a problem into smaller, more manageable
subproblems, solving each of those subproblems, and combining their results to arrive at a
solution for the original problem.

Key Concepts of Recursion:

 Base Case: This is a condition under which the recursive function stops calling itself. It
prevents infinite recursion and eventual program crash due to stack overflow. The base
case usually represents the simplest version of the problem.

 Recursive Case: This is the part of the function that includes the recursive call. It reduces
the problem size with each call, moving closer to the base case.
Recursion Function Example

def fibonacci(n):
""" Calculate the nth Fibonacci number using recursion.
Parameters: n (int): A non-negative integer Returns: int:
The nth Fibonacci number """ Formula:
# Base cases: Value(0) = 0
if n == 0: Value(1) = 1
return 0
elif n == 1: Value(n) = Value(n-1) + Value(n-
return 1 2)
# Recursive case:
else: return fibonacci(n - 1) + fibonacci(n - 2) Fibonacci Series
0, 1, 1, 2, 3, 5, 8, 13, 21, 34 …

# Example usage
result = fibonacci(6)
print(f"The 6th Fibonacci number is {result}")
Homework time 
HW-3: Factorial Calculator Using Recursion and Iteration :

1. Create a module, give a name whatever you want.


2. Create two functions «factorial_recursive» and «factorial_iterative».
3. Take an integer from the user, if the user does not enter a valid value, warn the user and take
an integer number again until a valid integer is entered.
4. Entered number must be lower than 50. Otherwise print a warning message and retake an
integer number.
5. Call «factorial_recursive» and «factorial_iterative» functions print the results.
6. Did you get the same results? I will run your codes, if it doesn't give the same results then
this requirement will be considered as failed.

 Write your codes in a text file or word document


 Upload your homework to Aybuzem until October 24th
 Everyone will run their codes on https://www.online-python.com/
Summary and Next Week's Topics

Recap of Week 4-5:


 Modular Programming
 Functions
 Recursive Function
 Module-Class-Function Relations

Week 6-7:
 Lists
 Tuples
 Dictionaries
Thank You!
Any Question?
[email protected]

You might also like