Functions and Modules in python
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 namedgreet.print("Hello, welcome to Python programming!")is the code that executes when thegreet()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 ** 2def cube(x):
return x ** 3These 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_moduleprint(my_module.square(5)) # Output: 25
print(my_module.cube(3)) # Output: 27This illustrates how modules can organize code and promote reusability across projects.










