Functions in Python
Teach Python a new trick once, then reuse it forever
def, then call it whenever you need it — instead of copying the same lines again and again.
- define a function with
defand call it, - send information in with parameters and arguments,
- send a result back with
return, - tell a local variable from a global one (scope),
- explain why functions make code shorter and clearer.
1. What is a function?
A function is like a little machine. You give it something, it does its job, and it can hand something back. A juicer is a good picture: you put in oranges (the input), it squeezes (the work), and out comes juice (the output). You built the juicer once, but you can use it every morning.
In code, a function lets you package a set of steps under one name. Then you run all those steps just by writing the name — this is called calling the function.
2. Defining a function with def
You create a function with the keyword def, a name, round brackets (), and a colon :. The steps inside are indented (usually 4 spaces).
def greet():
print("Hello!")
print("Welcome to Python.")
greet()
greet()
Output:
Hello!
Welcome to Python.
Hello!
Welcome to Python.
Notice: writing def greet(): only defines the function — nothing prints yet. The code runs only when you call it with greet(). We called it twice, so the message appears twice.