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.
Here’s how to define and use a function:
def greet_user(name): print(f"Hello, {name}!") greet_user("Alice")
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.
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!
The above is the detailed content of Python Functions and Modules: Writing Reusable Code Like a Pro. For more information, please follow other related articles on the PHP Chinese website!