def
- Python course
- Beginner
- Lesson 71/116
- 4 min
Learn to define functions with def.
Defining functions with def
A function is a reusable block of code. It is defined with the def keyword:
def greet():
print("Welcome")The function body is indented; this is how Python marks a block. The function is called with greet().
Functions prevent code repetition and split a program into parts. This improves both readability and maintainability.
Calling a function
A defined function is run by calling its name with parentheses:
def greet():
print("Welcome")
greet() # WelcomeWithout parentheses, greet just refers to the function object; it does not call it. This is a common mistake.
You can call a function as many times as you like; this prevents code repetition.
Practice Write a welcome function
Define a function called greet that prints print("Welcome"). Then call it with greet().
Starter code
# Define the greet functionSample solution
def greet():
print("Welcome")
greet()Expected output
Welcome
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is a valid function definition?
- def greet(): ... Correct answer
- function greet(): ...
- greet = def(): ...
- func greet(): ...
Explanation: It is defined as def greet():.
2 Complete the function call
greet____
greet()
Explanation: greet() calls the function.
3 Match the function parts
| Term | Meaning |
|---|---|
def |
Definition keyword |
greet |
Function name |
() |
Call parentheses |
: |
Body start |