A function is a named block of code you can run whenever you need it.
Instead of copying the same lines into three places, you write them
once, give them a name, and call that name. The def keyword defines
one.
def greet():
print("deploy starting")
Three parts matter here:
def tells Python you're defining a function.greet is the name. Pick something that says what it does.Defining a function does not run it. Python reads the def, remembers
the name, and moves on. The body sits idle until you call it.
You call a function by writing its name followed by parentheses:
greet()
greet()
That runs the body twice and prints the line twice. The parentheses are what trigger the call. The name on its own, without them, just refers to the function without running it.
Automation scripts repeat the same steps constantly: log a message, check a service, format a line of output. Wrapping each repeated step in a function keeps the script short and means you fix a bug in one place instead of five.
A function name also documents intent. restart_service() reads
better than eight lines of inline commands, and the next person
skimming your script understands it faster.
Function names follow the same style as variables: lowercase words
joined by underscores, like check_disk or send_alert. Use a verb,
since a function does something.
def name(): defines a function.def is the body.name() calls the function and runs its body.