Defining and calling functions
A function lets you name a block of code and run it on demand. You write it once with def, then call it whenever you need it.
Defining a function
Use the def keyword, a name, parentheses, and a colon. The indented lines below are the function body:
Python
Defining a function does not run it — it just teaches Python what the function does.
Calling a function
To actually run the body, call the function by writing its name followed by parentheses:
Python
Each call runs the whole body again, so you can reuse the same logic as many times as you like.
Why functions help
Without a function, you'd repeat the same lines everywhere. With one, you write the logic once and call it by name — and if you need to change it, you only edit it in one place.
Key takeaways
- Define a function with
def name():and an indented body. - Defining does not run the code; calling with
name()does. - Call a function as many times as you need to reuse its logic.
No comments yet. Add the first comment to start the discussion.