Defining Functions

Creating Reusable Code with Functions

Functions are reusable blocks of code that perform a specific task. You define a function with the def keyword, then call it by name whenever you need it.
python
def greet():
    print("Hello!")
    print("Welcome to Python!")

# Call the function
greet()
greet()  # You can call it multiple times!

Functions with Parameters

Functions can accept parameters — values you pass in when calling the function, making them flexible and reusable.
python
def greet(name):
    print(f"Hello, {name}!")

greet("Alice")
greet("Bob")

Tip:Functions help you follow the DRY principle: Don't Repeat Yourself. If you find yourself writing the same code twice, put it in a function!

PlaygroundPython
Output
Click "Run" to see output

💬 Got questions? Ask me anything!