Loading...
Loading...
Create reusable blocks of code with def
A function is a named block of reusable code. Instead of writing the same code multiple times, you write it once inside a function, then call the function whenever you need it.
def greet():
print("Hello!")
print("Welcome to the program!")
# Call the function
greet()
greet() # Works again!| Part | What it means |
|---|---|
| `def` | Keyword that **defines** a function |
| `greet` | **Function name** — you choose this, like a variable name |
| `()` | Parentheses — marks it as a function (can hold parameters) |
| `:` | Colon — ends the function header |
| indented body | The code that runs when the function is called |
| `greet()` | **Calling** the function — this runs the body |
def say_hello():
print("Hello, Python!")
print("Start")
say_hello()
print("Middle")
say_hello()
print("End")Output:
Start
Hello, Python!
Middle
Hello, Python!
EndStep by step:
| ❌ Wrong | Why | ✅ Right |
|---|---|---|
| Defining a function but never calling it | The code never runs! | Add `greet()` after the definition |
| Forgetting the colon `:` after `def name():` | Syntax error | Always end the header with `:` |
| Misspelling the function name when calling | NameError: `greet` is not defined | Use the same name you defined |
| Empty function body | SyntaxError: need at least one indented line | Use `pass` as a placeholder: `def f(): pass` |
Define a function called countdown that prints numbers from 3 to 1 (on separate lines), then prints "Go!". Call the function twice.
def countdown():
print(3)
print(2)
print(1)
print("Go!")
countdown()
countdown()