DEV Community

Aishwarya Raj
Aishwarya Raj

Posted on

Python Functions and Modules: Writing Reusable Code Like a Pro

Why Functions Matter (Hint: Less Code Repetition)

In Python, functions let you create a block of code that you can reuse anytime by calling its name. Define it once, then call it wherever you need it—no copy-pasting required.


Function Basics: The Recipe for Success

Here’s how to define and use a function:

def greet_user(name):
    print(f"Hello, {name}!")

greet_user("Alice")
Enter fullscreen mode Exit fullscreen mode
  • def defines the function.
  • Parameters (like name) allow input, making functions adaptable.
  • Return Values give you results back, so it’s not all output.

Modules: Libraries for Everything

Python’s modules are like cheat codes for functions—libraries that come preloaded with code you can use. No need to reinvent the wheel! Import them using import:

import math
print(math.sqrt(16))  # Outputs: 4.0
Enter fullscreen mode Exit fullscreen mode

Popular modules like math, random, and datetime save time and effort. If you’re building something big, you can even create custom modules.


Practical Example: Creating Your Own Module

Say you need to use greet_user across multiple files. Just save it in a .py file (like greetings.py), then import it wherever you need.

# In greetings.py
def greet_user(name):
    print(f"Hello, {name}!")

# In another file
from greetings import greet_user
greet_user("Alice")
Enter fullscreen mode Exit fullscreen mode

Functions and modules make your code smarter, faster, and reusable.
Cheers to coding smarter, not harder!

Top comments (2)

Collapse
 
latex_wei profile image
LaTex wei

Thank you, this is a fundational concept for being a software engineer.

Collapse
 
sarvabharan profile image
Sarva Bharan

👏🏻 good content