Skip to content
$ lynuxpro
← Python for DevOps

LESSON 2 OF 19 · BEGINNER · 12 MIN

Variables, types and control flow

Free previewLesson 2 of the 2 free lessons in this Pro course.Unlock all 19

HOW IT WORKSFacts, decisions and loops

Variableshost, port, cpuif / elif / elsedecidefor / whilerepeatActionalert, retry, nextResultprinted or returned
1/5

Variables store facts: text, numbers, true or false.

cpu = 91

In simple words

  • Variable: a name that points to a value, such as count = 3.
  • Type: the kind of value: str (text), int (whole number), float (decimal), bool (True or False).
  • if / elif / else: run different code depending on a condition.
  • for / while loop: repeat code for each item, or while a condition stays true.

Big picture

A program stores facts (variables), makes decisions (if) and repeats work (loops). That is nearly all of programming. In DevOps, the facts are things like a server name, a port or a list of hosts.

Variables and basic types

A variable is a name for a value. Python works out the type for you.

TypeExampleUsed for
str"web-01"text
int8080whole numbers
float0.75decimals
boolTrue, Falseyes or no
NoneNone"nothing here"
host = "web-01"port = 8080healthy = Trueprint(f"{host}:{port} healthy={healthy}")
NORMALpythonutf-8 · 4L
web-01:8080 healthy=True
OUTPUTterminalutf-8 · 1L

The f"..." is an f-string: it puts variables inside text with {}.

Making decisions

cpu = 91if cpu > 90:    print("ALERT")elif cpu > 70:    print("warning")else:    print("ok")
NORMALpythonutf-8 · 7L
ALERT
OUTPUTterminalutf-8 · 1L

Python uses indentation (4 spaces) to show what is inside the if. Do not mix tabs and spaces.

Comparisons: == equal, != not equal, > < >= <=. Combine with and, or, not.

Loops

servers = ["web-01", "web-02", "db-01"]for name in servers:    print("checking", name) tries = 0while tries < 3:    tries += 1print("tries:", tries)
NORMALpythonutf-8 · 8L
checking web-01checking web-02checking db-01tries: 3
OUTPUTterminalutf-8 · 4L
KeywordMeaning
for x in itemsdo this once per item
while conditionrepeat while true
breakstop the loop now
continueskip to the next item
range(5)the numbers 0 to 4

Truthy and falsy

Empty things count as false: "", 0, [], {}, None. So if not servers: means "the list is empty".

A small worked example

Check a list of ports and report which ones are open:

checks = {"web": 80, "ssh": 22, "db": 5432}open_ports = {80, 22} for name, port in checks.items():    status = "open" if port in open_ports else "CLOSED"    print(f"{name:<5} {port:>5} {status}")
NORMALpythonutf-8 · 6L
web      80 openssh      22 opendb     5432 CLOSED
OUTPUTterminalutf-8 · 3L

"open" if ... else "CLOSED" is a one-line if. The :<5 and :>5 inside the f-string line up the columns.

Turning types into each other

CallResult
int("8080")8080
str(8080)"8080"
float("0.75")0.75
bool("")False
int("abc")raises ValueError

Environment variables and file contents always arrive as text, so convert them yourself.

Common mistakes

  • Using = instead of == in a condition. One stores, two compares.
  • Wrong indentation. Python raises IndentationError.
  • Reading numbers as text. input() and environment variables give strings. Use int("8080").

Summary

Variables hold values, if decides, for and while repeat. Indentation is part of the syntax.

CHECK YOUR UNDERSTANDING

3 quick questions

  1. 1. What does `if not servers:` check when servers is a list?

  2. 2. What shows which lines belong inside an `if` in Python?

  3. 3. Environment variables arrive as which type?

You've finished the free preview of Python for DevOps

Upgrade to Pro to unlock the remaining 17 lessons, every practice lab and a certificate when you finish.

See plans