Why functions?
Stop repeating yourself: name a piece of work and reuse it.
🎬 Video version coming soon — read it now
A function is a named piece of code that does one job. You write it once and call it whenever you need that job done. You've already used plenty: print(), len(), input(), sorted(). Now you'll write your own.
The problem functions solve
# Without functions: the same three lines, again and again
print("-" * 30)
print("IT Vizag Python Course")
print("-" * 30)
# ... later ...
print("-" * 30)
print("IT Vizag Python Course")
print("-" * 30)If you want to change the dashes to stars, you have to find every copy. Miss one and your output is inconsistent.
The same thing with a function
def banner():
print("-" * 30)
print("IT Vizag Python Course")
print("-" * 30)
banner()
banner()defstarts a function definition, followed by its name, brackets and a colon.- The indented lines are the body.
- Defining a function doesn't run it. Calling it with
banner()does.
Change the function once and every call changes with it.
Why professionals love functions
- Don't repeat yourself (DRY): one place to fix, one place to improve.
- Readable:
send_receipt(order)explains itself; 20 lines of code don't. - Testable: you can check a small function on its own.
- Teamwork: one person writes
calculate_tax(), another uses it without reading its insides.
Naming functions
Use verbs in snake_case that say what the function does: calculate_total, send_email, is_valid_phone. If you need "and" in the name, it's probably doing two jobs.
In one line
A function is a named, reusable piece of code: define it once with def, then call it as many times as you need.
Share with a friend