Course Content
🎁 Bonus Modules (Integrated Throughout)
Data Analytics
Functions and Modules

 

In any program, some parts of code may need to be reused. Python offers functions and modules to help us organize and reuse code in a clean and manageable way.


What is a Function?

A function is a block of code that performs a specific task. It runs only when it is called.

 

Why use functions?

  • To avoid repeating code
  • To organize your program better
  • To make your code more readable and reusable


Function with Parameters

Functions can accept parameters (inputs) and return values.

def add(a, b):
return a + b

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


Default and Keyword Arguments

You can give a default value to a parameter.

def greet(name="Guest"):
print(f"Hello, {name}!")

greet("Alice")
greet() # Uses default value

 

You can also use keyword arguments:

def profile(name, age):
print(f"{name} is {age} years old.")

profile(age=25, name="John")


Return Statement

Functions can return a value using return.

def square(num):
return num * num

output = square(4) # output will be 16


What is a Module?

A module is simply a Python file that contains functions, variables, or classes. You can use a module in another file using the import keyword.


Using Built-in Modules

Example: Using the math module

import math

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


Creating Your Own Module

Suppose you have a file named mymodule.py:

# mymodule.py
def greet(name):
return f"Hello, {name}!"

 

Then in another file:

import mymodule

print(mymodule.greet("Emma"))


Using from Keyword

You can import specific functions:

from math import pi

print(pi) # Output: 3.141592653589793


Summary

  • Use functions to reuse and organize your code.
  • Functions can take parameters and return values.
  • A module is a file that contains Python code.
  • Use import to use code from other modules.
  • Python has many built-in modules (like math, random, etc.)
0% Complete
WhatsApp Icon

Hi Instagram Fam!
Get a FREE Cheat Sheet on System Design.

Hi LinkedIn Fam!
Get a FREE Cheat Sheet on System Design

Loved Our YouTube Videos? Get a FREE Cheat Sheet on System Design.