Sitemap

Functions and Modules in python

2 min readDec 19, 2023

--

Press enter or click to view image in full size

Functions in Python

Functions are like reusable blocks of code that perform specific tasks. They help in organizing code, improving readability, and reducing repetition. In Python, defining a function is straightforward:

# Creating a simple function
def greet():
print("Hello, welcome to Python programming!")
# Calling the function
greet()

Here’s what this code snippet does:

  • def greet(): defines a function named greet.
  • print("Hello, welcome to Python programming!") is the code that executes when the greet() function is called.
  • greet() is the function call that triggers the execution of the code within the function.

Get Uzma Tabassum’s stories in your inbox

Join Medium for free to get updates from this writer.

Functions allow us to encapsulate a piece of code so that it can be executed multiple times with ease, without having to rewrite it each time.

Modules in Python

Modules in Python are files containing Python code. They can define functions, classes, and variables that can be reused in other Python files. For instance:

# Creating a module named my_module.py
# my_module.py
def square(x):
return x ** 2
def cube(x):
return x ** 3

These functions, square() and cube(), are now part of the my_module module and can be imported into other Python files using the import statement:

# Using functions from the module
import my_module
print(my_module.square(5))  # Output: 25
print(my_module.cube(3)) # Output: 27

This illustrates how modules can organize code and promote reusability across projects.

--

--