Functions and Modules

🧩 Functions and Modules

Description: Learn to organize code into reusable blocks with functions and modules. This makes your code modular, readable, and reusable.


Defining and Calling a Function

This function prints a greeting message when called.

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



Function with Parameters

The function accepts a name and prints a personalized message.

def greet(name): print("Hello", name)
greet("Alice")
Hello Alice



Returning a Value

This function returns the square of a number.

def square(x): return x * x
print(square(4))
16



Multiple Parameters

Adds two numbers and returns the result.

def add(a, b): return a + b
print(add(5, 3))
8



Default Arguments

Uses a default name if none is provided.

def greet(name="Guest"): print("Hello", name)
greet()
greet("Bob")
Hello Guest
Hello Bob



Keyword Arguments

Arguments are passed using key=value syntax.

def introduce(name, age): print(name, "is", age, "years old") introduce(age=25, name="John")
John is 25 years old



Variable Number of Arguments

Use *args to accept many arguments.

def total(*args): return sum(args)
print(total(1, 2, 3, 4))
10



Function with Conditional Logic

Returns if a number is even or odd.

def check_even(num): if num % 2 == 0: return "Even" else: return "Odd"
print(check_even(7))
Odd



Importing a Built-in Module

Using the math module to compute square root.

import math
print(math.sqrt(16))
4.0



Import with Alias

Alias a module name for easier use.

import math as m
print(m.pi)
3.141592653589793



From Import

Import only a part of a module.

from math import pow
print(pow(2, 3))
8.0



Creating Your Own Module

Create a file mytools.py and define a function:

# mytools.py
def say_hello(): print("Hello from module!")

Then use it like this:

import mytools
mytools.say_hello()
Hello from module!



Module with Return Value

# calculator.py
def multiply(x, y): return x * y
import calculator
print(calculator.multiply(3, 4))
12



Using Built-in random Module

import random
print(random.randint(1, 10))
# Random number between 1 and 10



Docstrings in Functions

Use triple quotes to describe what a function does.

def add(a, b): """Returns the sum of a and b""" return a + b
print(add.__doc__)
Returns the sum of a and b