Loading...

Go Back

Next page
Go Back Course Outline

Python Full Course


Functions and Modules in Python

Python Basics

Functions and Modules in Python

Functions and modules help you organize and reuse code in Python. They make your programs cleaner, more efficient, and easier to manage.

1. Functions

A function is a block of reusable code that performs a specific task. You define it using the def keyword.

Function Syntax:
def greet(name):
    print("Hello, " + name + "!")
Calling a Function:
greet("Alice")  # Output: Hello, Alice!
Function with Return Value:
def add(a, b):
    return a + b

result = add(5, 3)
print(result)  # Output: 8
2. Modules

A module is a Python file (.py) that contains functions, variables, or classes you can use in other programs.

Creating a Module (saved as math_utils.py):
def square(x):
    return x * x

def cube(x):
    return x * x * x
Importing and Using a Module:
import math_utils

print(math_utils.square(4))  # Output: 16
print(math_utils.cube(3))    # Output: 27
Import Specific Functions:
from math_utils import square

print(square(5))  # Output: 25
Built-in Modules:

Python comes with many useful built-in modules like:

  • math – for mathematical functions
  • random – for random number generation
  • datetime – for working with dates and times
Example:
import math

print(math.sqrt(16))  # Output: 4.0
Tip:

Use functions to keep your code organized and avoid repetition. Use modules to break large programs into smaller, manageable pieces.

Defining and Calling Functions

Functions are reusable blocks of code.


                                def greet():
                            print("Hello, welcome to Python!")
                        
                        greet()
Hello, welcome to Python!

Function Arguments

Default Arguments


                                def power(base, exponent=2):
                            return base ** exponent
                        
                        print(power(3))
                        print(power(3, 3))
9 27


Return Values


                                def square(n):
                            return n * n
                        
                        result = square(4)
                        print(result)
16

Variable Scope

Local Scope


                                def local_example():
                            x = 10
                            print(x)
                        
                        local_example()
10

Global Scope


                                y = 50
                        
                        def global_example():
                            global y
                            y += 10
                            print(y)
                        
                        global_example()
60

Lambda Functions


                                square = lambda x: x * x
                        print(square(5))
25

Creating a Custom Module


                                # mymodule.py
                        def greet(name):
                            return f"Hello, {name}!"
Create mymodule.py and import it in another script.


Error Handling

Basic Try-Except


                                try:
                            x = 5 / 0
                        except ZeroDivisionError:
                            print("Cannot divide by zero!")
Cannot divide by zero!

Raising Exceptions


                                def check_age(age):
                            if age < 18:
                                raise ValueError("Must be 18 or older")
                            return "Allowed"
                        
                        print(check_age(20))
Allowed

Custom Exceptions


                                class CustomError(Exception):
                            pass
                        
                        try:
                            raise CustomError("This is a custom exception")
                        except CustomError as e:
                            print(e)
This is a custom exception
Go Back

Next page