Python Functions: Define and Call Your Own
What Is a Function in Python?
A function is a named block of code that does one job. You write the code once, give it a name, and then run it whenever you want by calling that name.
You already know the idea from chapter 2: print() is a function, a named mini-machine. So are len(), input(), int() and sorted(). They are built-in functions: Python made them for you. In this chapter, you'll build your own.
Think of it like a recipe card. You write the steps for pancakes once and give the card a title. Whenever you want pancakes, you don't write the steps again: you pick up the card called "pancakes" and follow it.
def say_hello():
print("Hello!")
print("Welcome to LivePython.")
say_hello()
say_hello()Hello! Welcome to LivePython. Hello! Welcome to LivePython.
Two lines of code, written once, printed twice.
Two steps: define, then call
| Step | What you write | What happens |
|---|---|---|
| Define | def say_hello(): and an indented body | Python remembers the lines under that name. Nothing prints yet. |
| Call | say_hello() | Python runs those lines, top to bottom. |
- Built-in functions come with Python:
print(),len(),input(). - Your own functions are made with
def, then used exactly the same way: the name, then brackets.
Common beginner doubt: "Is a function the same as a loop?" No. A loop repeats lines right where it is, straight away. A function stores lines under a name, and runs them only when, and wherever, you call it.
A function is a named block of code: define it once, call it by its name whenever you need it.