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

FoPM3 Functions and Modules

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

FoPM3 Functions and Modules

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Functions and Modules in Python

Functions and modules are two of the most essential concepts in Python and any programming
language. They allow for more organized, modular, and reusable code. Below, I'll break down each
subtopic and provide explanations, followed by examples to clarify their use in practice.

1. Defining Functions

A function in Python is a block of reusable code that performs a specific task. Functions help break
down programs into smaller, more manageable parts, making the code more readable and reducing
redundancy.

To define a function, you use the def keyword followed by the function name and parentheses ():

def function_name(parameters):

# Function body

return result

• function_name: The name of the function that will be used to call it.

• parameters: Variables that act as inputs to the function (optional).

• return: The value that the function will send back to the caller (optional).

Example:

def greet(name):

return f"Hello, {name}!"

print(greet("Alice")) # Output: Hello, Alice!

2. Function Parameters and Return Values

• Parameters are inputs to the function. When a function is called, you pass values
(arguments) to these parameters. Python allows for various types of parameters, including:

o Positional arguments: The arguments are assigned to parameters based on their


position.

o Keyword arguments: The arguments are assigned by explicitly naming the


parameters.
o Default parameters: Parameters with default values that don't require a value
during function calls.

• Return Values: A function can send a value back to the caller using the return keyword. If
no return is used, the function implicitly returns None.

Example:

def multiply(a, b=2): # b has a default value of 2

return a * b

result = multiply(5) # Only 1 argument, so b uses its default value

print(result) # Output: 10

result = multiply(5, 3) # Both arguments provided

print(result) # Output: 15

3. Scope: Local vs. Global Variables

• Local Variables: These are variables defined inside a function. They are accessible only
within that function and don't affect or interact with variables outside of the function.

• Global Variables: Variables defined outside of any function and can be accessed
throughout the code, including within functions. However, if you want to modify a global
variable inside a function, you must explicitly declare it using the global keyword.

Example:

x = 10 # Global variable

def my_function():

x = 5 # Local variable

print("Inside function:", x)

my_function() # Output: Inside function: 5


print("Outside function:", x) # Output: Outside function: 10

# Using the global keyword

def modify_global():

global x

x = 20

modify_global()

print("Modified global:", x) # Output: Modified global: 20

4. Built-in Functions and Importing Modules

Python provides numerous built-in functions like print(), len(), sum(), etc., which are available by
default.

To extend Python's functionality, you can import modules. Modules are collections of related
functions and variables grouped into a single file or package. Python provides many standard
modules like math, random, datetime, and more. To use them, you must first import them using the
import keyword.

Example of Importing a Module:

import math

# Using a function from the math module

result = math.sqrt(16)

print(result) # Output: 4.0

You can also import specific functions from a module:

python

Copy code

from math import sqrt

print(sqrt(25)) # Output: 5.0


5. Writing and Using Custom Modules

A custom module is simply a Python file containing functions, variables, and classes that you can
import into other programs. To create a module, you write a Python file and save it with a .py
extension. You can then import that file into another script to use its functionality.

Example:

1. Create a module mymath.py:

# mymath.py

def add(a, b):

return a + b

def subtract(a, b):

return a - b

2. Use the module in another Python file:

import mymath

result = mymath.add(10, 5)

print(result) # Output: 15

You can also use from to import specific functions from a custom module:

python

Copy code

from mymath import subtract

print(subtract(10, 3)) # Output: 7

6. Introduction to Recursion
Recursion occurs when a function calls itself in its definition. It’s often used to solve problems that
can be divided into similar sub-problems, such as calculating the factorial of a number or finding
the greatest common divisor (GCD).

When writing recursive functions, it’s essential to define a base case to prevent infinite recursion.

Example: Factorial Calculation Using Recursion:

def factorial(n):

if n == 1: # Base case

return 1

else:

return n * factorial(n - 1) # Recursive case

print(factorial(5)) # Output: 120

Exercises:

Exercise 1: Creating a Reusable Function (GCD Calculation)

The greatest common divisor (GCD) of two numbers is the largest positive integer that divides
both numbers without leaving a remainder. You can use recursion to calculate the GCD using
Euclid's algorithm.

Example:

def gcd(a, b):

if b == 0:

return a

else:

return gcd(b, a % b)

print(gcd(48, 18)) # Output: 6

Exercise 2: Importing and Using Standard Python Libraries

Use Python’s math and random libraries to perform various tasks.


Example using math and random:

import math

import random

# Generate a random number between 1 and 100

random_number = random.randint(1, 100)

print("Random number:", random_number)

# Calculate the square root of the random number

sqrt_value = math.sqrt(random_number)

print("Square root:", sqrt_value)

Summary:

• Defining Functions allows you to encapsulate functionality and reuse code.

• Function Parameters can be passed to functions, and return values allow them to send
information back to the caller.

• Scope distinguishes between variables defined locally inside functions and globally in the
program.

• Python provides many built-in functions and modules that extend its functionality.

• You can create your own custom modules to organize code across multiple files.

• Recursion allows for elegant solutions to certain problems but requires a base case to
prevent infinite loops.

You might also like