🧩 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.
greet()
Function with Parameters
The function accepts a name and prints a personalized message.
greet("Alice")
Returning a Value
This function returns the square of a number.
print(square(4))
Multiple Parameters
Adds two numbers and returns the result.
print(add(5, 3))
Default Arguments
Uses a default name if none is provided.
greet()
greet("Bob")
Hello Bob
Keyword Arguments
Arguments are passed using key=value syntax.
Variable Number of Arguments
Use *args to accept many arguments.
print(total(1, 2, 3, 4))
Function with Conditional Logic
Returns if a number is even or odd.
print(check_even(7))
Importing a Built-in Module
Using the math module to compute square root.
print(math.sqrt(16))
Import with Alias
Alias a module name for easier use.
print(m.pi)
From Import
Import only a part of a module.
print(pow(2, 3))
Creating Your Own Module
Create a file mytools.py and define a function:
def say_hello(): print("Hello from module!")
Then use it like this:
mytools.say_hello()
Module with Return Value
def multiply(x, y): return x * y
print(calculator.multiply(3, 4))
Using Built-in random Module
print(random.randint(1, 10))
Docstrings in Functions
Use triple quotes to describe what a function does.
print(add.__doc__)