The def Keyword and Syntax
🏷️ Functions / Defining and Calling Functions
🎯 Context Introduction
Functions are reusable blocks of code that perform a specific task. Think of them as a recipe: you define the steps once, and then you can use that recipe whenever you need it. The def keyword is how you tell Python, "Hey, I'm about to define a new function." This is one of the most fundamental concepts in Python, and mastering it will make your code cleaner, more organized, and much easier to maintain.
⚙️ What is the def Keyword?
The def keyword is Python's way of starting a function definition. It signals to Python that the code that follows is a reusable block that can be called later. Here's what happens when you use def:
- def is always followed by the function name you choose
- The function name is followed by parentheses ( )
- Inside the parentheses, you can place parameters (optional)
- The line ends with a colon :
- The function body is indented below the definition line
A simple example of a function definition looks like this:
def greet(): print("Hello, welcome to Python!")
To use this function, you would call it by its name:
greet()
This would output: Hello, welcome to Python!
📊 Breaking Down the Syntax
Let's examine each part of the function definition in detail:
| Component | Purpose | Example |
|---|---|---|
| def keyword | Tells Python you are defining a function | def |
| Function name | The name you use to call the function later | calculate_total |
| Parentheses () | Holds parameters (inputs) the function needs | ( ) |
| Colon : | Marks the end of the function header | : |
| Indented body | The code that runs when the function is called | return a + b |
A complete example with all components:
def calculate_total(price, tax_rate): total = price + (price * tax_rate) return total
🛠️ Function Naming Rules
When naming your functions, follow these simple rules:
- Function names must start with a letter or underscore, not a number
- Use lowercase letters and separate words with underscores (snake_case)
- Choose descriptive names that explain what the function does
- Avoid using Python reserved words like print, if, or for as function names
Good function names: - get_user_input - process_data - send_email_notification
Poor function names: - func1 - do_stuff - x
🕵️ Parameters vs Arguments
These two terms are often confused, but they have distinct meanings:
- Parameters are the variables listed inside the parentheses in the function definition
- Arguments are the actual values you pass to the function when you call it
In this example:
def multiply(a, b): return a * b
result = multiply(5, 3)
Here, a and b are parameters. The values 5 and 3 are arguments.
📋 Common Function Patterns
Here are three common patterns you will use frequently:
Pattern 1: Function with no parameters def display_banner(): print("=" * 50) print("SYSTEM STATUS REPORT") print("=" * 50)
Pattern 2: Function with one parameter def square_number(num): return num * num
Pattern 3: Function with multiple parameters def create_full_name(first, last): return first + " " + last
✅ Key Takeaways
- The def keyword is how you start every function definition in Python
- Always end the function header with a colon :
- Indent the function body consistently (4 spaces is standard)
- Function names should be descriptive and use snake_case
- Parameters go inside the parentheses, arguments are the values you pass
- Functions can have zero, one, or multiple parameters
- Use return to send a value back from the function
Remember: Functions help you avoid repeating code. If you find yourself writing the same logic more than once, it's time to create a function. Start simple, practice often, and soon defining functions will become second nature.
The def keyword in Python creates a reusable block of code called a function, which you can run by calling its name.
📘 Example 1: Defining a function with no parameters
This example shows the simplest possible function — it takes no inputs and prints a fixed message.
def greet():
print("Hello, engineer!")
📤 Output: (no output until called)
📘 Example 2: Calling a function after defining it
This example shows how to execute a function by writing its name followed by parentheses.
def greet():
print("Hello, engineer!")
greet()
📤 Output: Hello, engineer!
📘 Example 3: Function with one parameter
This example shows how to pass a single value into a function so it can use that value.
def greet(name):
print("Hello, " + name + "!")
greet("Alice")
📤 Output: Hello, Alice!
📘 Example 4: Function with two parameters and a return value
This example shows a function that takes two numbers, adds them, and sends the result back to where it was called.
def add(a, b):
result = a + b
return result
sum_value = add(5, 3)
print(sum_value)
📤 Output: 8
📘 Example 5: Function with a default parameter value
This example shows how to give a parameter a default value, so the function works even when that argument is omitted.
def greet(name="engineer"):
print("Hello, " + name + "!")
greet()
greet("Bob")
📤 Output: Hello, engineer!
Hello, Bob!
📘 Example 6: Function that returns a boolean result
This example shows a practical function that checks a condition and returns True or False.
def is_even(number):
if number % 2 == 0:
return True
else:
return False
print(is_even(4))
print(is_even(7))
📤 Output: True
False
Comparison Table: Function Syntax Variations
| Feature | Syntax Example | Purpose |
|---|---|---|
| No parameters | def my_func(): |
Runs same code every time |
| One parameter | def my_func(x): |
Uses one input value |
| Two parameters | def my_func(a, b): |
Uses two input values |
| Return value | def my_func(): return x |
Sends a result back |
| Default parameter | def my_func(x=5): |
Provides a fallback value |
🎯 Context Introduction
Functions are reusable blocks of code that perform a specific task. Think of them as a recipe: you define the steps once, and then you can use that recipe whenever you need it. The def keyword is how you tell Python, "Hey, I'm about to define a new function." This is one of the most fundamental concepts in Python, and mastering it will make your code cleaner, more organized, and much easier to maintain.
⚙️ What is the def Keyword?
The def keyword is Python's way of starting a function definition. It signals to Python that the code that follows is a reusable block that can be called later. Here's what happens when you use def:
- def is always followed by the function name you choose
- The function name is followed by parentheses ( )
- Inside the parentheses, you can place parameters (optional)
- The line ends with a colon :
- The function body is indented below the definition line
A simple example of a function definition looks like this:
def greet(): print("Hello, welcome to Python!")
To use this function, you would call it by its name:
greet()
This would output: Hello, welcome to Python!
📊 Breaking Down the Syntax
Let's examine each part of the function definition in detail:
| Component | Purpose | Example |
|---|---|---|
| def keyword | Tells Python you are defining a function | def |
| Function name | The name you use to call the function later | calculate_total |
| Parentheses () | Holds parameters (inputs) the function needs | ( ) |
| Colon : | Marks the end of the function header | : |
| Indented body | The code that runs when the function is called | return a + b |
A complete example with all components:
def calculate_total(price, tax_rate): total = price + (price * tax_rate) return total
🛠️ Function Naming Rules
When naming your functions, follow these simple rules:
- Function names must start with a letter or underscore, not a number
- Use lowercase letters and separate words with underscores (snake_case)
- Choose descriptive names that explain what the function does
- Avoid using Python reserved words like print, if, or for as function names
Good function names: - get_user_input - process_data - send_email_notification
Poor function names: - func1 - do_stuff - x
🕵️ Parameters vs Arguments
These two terms are often confused, but they have distinct meanings:
- Parameters are the variables listed inside the parentheses in the function definition
- Arguments are the actual values you pass to the function when you call it
In this example:
def multiply(a, b): return a * b
result = multiply(5, 3)
Here, a and b are parameters. The values 5 and 3 are arguments.
📋 Common Function Patterns
Here are three common patterns you will use frequently:
Pattern 1: Function with no parameters def display_banner(): print("=" * 50) print("SYSTEM STATUS REPORT") print("=" * 50)
Pattern 2: Function with one parameter def square_number(num): return num * num
Pattern 3: Function with multiple parameters def create_full_name(first, last): return first + " " + last
✅ Key Takeaways
- The def keyword is how you start every function definition in Python
- Always end the function header with a colon :
- Indent the function body consistently (4 spaces is standard)
- Function names should be descriptive and use snake_case
- Parameters go inside the parentheses, arguments are the values you pass
- Functions can have zero, one, or multiple parameters
- Use return to send a value back from the function
Remember: Functions help you avoid repeating code. If you find yourself writing the same logic more than once, it's time to create a function. Start simple, practice often, and soon defining functions will become second nature.
Interactive Views
You are currently in 📚 All-in-One mode. Use the tabs at the top to switch to 📖 Theory Only or 💻 Code Only views.
The def keyword in Python creates a reusable block of code called a function, which you can run by calling its name.
📘 Example 1: Defining a function with no parameters
This example shows the simplest possible function — it takes no inputs and prints a fixed message.
def greet():
print("Hello, engineer!")
📤 Output: (no output until called)
📘 Example 2: Calling a function after defining it
This example shows how to execute a function by writing its name followed by parentheses.
def greet():
print("Hello, engineer!")
greet()
📤 Output: Hello, engineer!
📘 Example 3: Function with one parameter
This example shows how to pass a single value into a function so it can use that value.
def greet(name):
print("Hello, " + name + "!")
greet("Alice")
📤 Output: Hello, Alice!
📘 Example 4: Function with two parameters and a return value
This example shows a function that takes two numbers, adds them, and sends the result back to where it was called.
def add(a, b):
result = a + b
return result
sum_value = add(5, 3)
print(sum_value)
📤 Output: 8
📘 Example 5: Function with a default parameter value
This example shows how to give a parameter a default value, so the function works even when that argument is omitted.
def greet(name="engineer"):
print("Hello, " + name + "!")
greet()
greet("Bob")
📤 Output: Hello, engineer!
Hello, Bob!
📘 Example 6: Function that returns a boolean result
This example shows a practical function that checks a condition and returns True or False.
def is_even(number):
if number % 2 == 0:
return True
else:
return False
print(is_even(4))
print(is_even(7))
📤 Output: True
False
Comparison Table: Function Syntax Variations
| Feature | Syntax Example | Purpose |
|---|---|---|
| No parameters | def my_func(): |
Runs same code every time |
| One parameter | def my_func(x): |
Uses one input value |
| Two parameters | def my_func(a, b): |
Uses two input values |
| Return value | def my_func(): return x |
Sends a result back |
| Default parameter | def my_func(x=5): |
Provides a fallback value |