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")
-
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
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")
Functions and modules make your code smarter, faster, and reusable.
Cheers to coding smarter, not harder!
Top comments (2)
Thank you, this is a fundational concept for being a software engineer.
👏🏻 good content