LESSON · 1 OF 6

Defining functions with def

Defining functions with def

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.

The shape of a function

python
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.
  • The indented block below the colon is the body, the code that runs when the function is called.

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.

Calling a function

You call a function by writing its name followed by parentheses:

python
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.

Why this matters for DevOps

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.

Naming

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.

What this node covers

  • def name(): defines a function.
  • The indented block under def is the body.
  • name() calls the function and runs its body.
Spin up a fresh environment and practice live.
python-devops · fresh machine · ready in under a minute