Syntax, types & variables
Python is the language DevOps engineers reach for when a shell script gets too complicated: it reads almost like English, runs everywhere, and has a library for nearly every tool and cloud. This chapter covers how a Python program runs and how it stores values.
How Python runs your code
Python is interpreted: there's no separate compile step. You write code in a .py file and the Python interpreter reads and runs it from the top down, line by line. You can also type python3 on its own to get the REPL (the >>> prompt, like the Python console on this site), which runs each line as you type it. Great for trying things out.
$ python3 hello.py # run a file
$ python3 # interactive prompt
>>> 2 + 3
5
Indentation is the syntax
Many languages mark blocks with braces { }. Python uses indentation instead: everything indented under an if, loop or function belongs to it, and the block ends when the indentation goes back. The convention is 4 spaces. Mixing tabs and spaces, or indenting inconsistently, gives an IndentationError. Comments start with # and are ignored.
Variables are labels
A variable is a name that points at a value. You don't declare a type; Python works it out from the value, which is called dynamic typing. The same name can later point at something of a different type.
server = "web-01" # str
port = 8080 # int
load = 0.75 # float
healthy = True # bool
owner = None # "no value yet"
print(type(port)) # <class 'int'>
The core types:
- int: whole numbers, any size. float: numbers with a decimal point.
- str: text, in single or double quotes. Triple quotes span several lines.
- bool:
TrueorFalse(capitalised). - None: the absence of a value, what a function returns when it returns nothing.
Converting between types
input() always gives you a string, even if the user typed a number, so you convert it before doing maths: age = int(input("Age: ")). int(), float(), str() and bool() convert, and they raise an error if the conversion makes no sense (int("abc")).
Strings you'll use every day
name = "Demee"
print(f"Hello {name}, you have {3 * 2} alerts") # f-string: values inside {}
"web-01".upper() # 'WEB-01'
" text ".strip() # 'text' (trim spaces/newlines)
"a,b,c".split(",") # ['a', 'b', 'c']
"-".join(["2026", "09", "27"]) # '2026-09-27'
"error" in "fatal error" # True
"nginx.conf".endswith(".conf") # True
len("devops") # 6
Strings are immutable: methods like .upper() return a new string and leave the original unchanged. Lists, dicts and sets are mutable: you can change them in place. That difference explains a lot of surprising behaviour later.
Your first program, step by step
Make a file called hello.py (in VS Code, or nano hello.py in the terminal) and type this in:
# hello.py: my first script
name = input("What's your name? ")
servers = 3
print(f"Hi {name}! You look after {servers} servers.")
$ python3 hello.py
What's your name? Demee
Hi Demee! You look after 3 servers.
Line by line: the first line is a comment, ignored by Python. input() prints the question, waits for you to type and press Enter, and gives back what you typed as a string, which is stored in name. servers = 3 stores a number. The last line builds a sentence with an f-string and prints it. Python ran the lines from top to bottom, exactly once each; everything else in programming is about changing that order (decisions and loops, chapter 3).
Reading error messages
Errors aren't failure, they're Python telling you exactly what's wrong. Change {name} to {nme} and run it again:
Traceback (most recent call last):
File "hello.py", line 4, in <module>
print(f"Hi {nme}! You look after {servers} servers.")
NameError: name 'nme' is not defined. Did you mean: 'name'?
Read it from the bottom up. The last line says what went wrong (NameError: a name Python doesn't know), and the lines above say where (line 4). The errors you'll meet most at the start:
SyntaxError: Python can't even read the line. Usually a missing quote, bracket or colon. Look at the line it names and the one before it.IndentationError: a block isn't lined up, or tabs and spaces are mixed.NameError: a typo in a name, or using a variable before giving it a value.TypeError: can only concatenate str (not "int") to str: you tried"Total: " + 5. Text and numbers don't add; use an f-string (f"Total: {5}") orstr(5).ValueError: invalid literal for int():int("abc"), converting text that isn't a number.
Naming things
Names may contain letters, digits and underscores but can't start with a digit, and they're case-sensitive (Port and port are different). Python style is snake_case: max_retries, server_name. Values that never change are written in capitals by convention, TIMEOUT = 30. Good names make code read like a sentence; x and data2 make you guess.
Try it yourself
Ask for a server name and a port, then print a line like
web-01 listens on 8080.Show an answer
server = input("Server: ") port = input("Port: ") print(f"{server} listens on {port}")Ask how many servers there are and what one costs per month (it can have cents), then print the total cost. Remember
input()always gives text.Show an answer
count = int(input("How many servers? ")) price = float(input("Price per server: ")) print(f"Total: {count * price}")This line crashes. Why, and how do you fix it?
print("You have " + 3 + " alerts")Show an answer
It's a
TypeError:+can't join text and a number. Useprint(f"You have {3} alerts")orprint("You have " + str(3) + " alerts").