Your DevOps study space

Real explanations. Videos with tests. Fresh exams every time. Keep the streak alive and watch the XP stack up.

Control flow & functions · Python Docs · StackwisePlanDevOps Control flow & functions · Python Docs · StackwiseCodePython Control flow & functions · Python Docs · StackwiseBuildDocker Control flow & functions · Python Docs · StackwiseTestDevOps Control flow & functions · Python Docs · StackwiseReleaseGit Control flow & functions · Python Docs · StackwiseDeployKubernetes Control flow & functions · Python Docs · StackwiseOperateLinux Control flow & functions · Python Docs · StackwiseMonitorDevOps

Pick a topic

Eight tracks, each with docs, a cheat sheet, videos and tests.

How it works

One loop, repeated until it sticks.

Jump back in

Picked up from where you left off.

Free forever

Your DevOps journey starts with one click.

Sign in with Google or GitHub to open every chapter, video, test and challenge. Your progress is saved wherever you learn.

Control flow & functions

Control flow decides which lines run and how many times; functions package logic under a name so you can reuse it. Together they turn a list of statements into an actual program.

Making decisions

cpu = 85
if cpu > 90:
    print("critical")
elif cpu > 70:
    print("warning")
else:
    print("ok")

Python checks each condition from the top and runs only the first block that matches, then skips the rest. Here it prints "warning" and never looks at else. elif and else are optional.

Loops

A for loop runs once for each item in something iterable (a list, a string, a file, a range of numbers). A while loop keeps going as long as a condition stays true, which is right when you don't know in advance how many times, like retrying until a server answers.

for host in ["web-01", "web-02", "db-01"]:
    print("checking", host)

for i in range(3):          # 0, 1, 2 (stops before 3)
    print(i)

attempts = 0
while attempts < 5:
    attempts += 1           # without this the loop never ends
    if try_connect():
        break               # leave the loop early
  • break exits the loop immediately; continue skips to the next item.
  • range(start, stop, step) produces numbers; range(0, 10, 2) gives 0, 2, 4, 6, 8.
  • pass does nothing. It's a placeholder where Python needs a statement but you have nothing to write yet.

Functions

A function is a named, reusable block. You define it once with def and call it as often as you like, passing in values (arguments) that fill its parameters.

def disk_status(used, total=100):
    """Return a label for how full a disk is."""
    percent = used / total * 100
    if percent > 90:
        return "full"
    return "ok"

disk_status(95)              # 'full' (total defaults to 100)
disk_status(40, total=500)   # 'ok'
  • return sends a value back to whoever called the function and ends it. A function without return gives back None.
  • print only shows something on screen; it doesn't give the value back. Mixing these up is a very common beginner bug.
  • A parameter with = has a default, which makes it optional.
  • *args collects any extra positional arguments into a tuple, **kwargs collects extra named ones into a dict: def total(*args): return sum(args).
  • The string right under def is a docstring, the function's built-in documentation.
disk_status(95)the calldef disk_status(used, total=100)used = 95 total = 100parameters filled inpercent = 95.0the body runsreturn "full"arguments"full"back to caller
Arguments go in, the body runs once, return hands one value back and ends the function. total wasn't passed, so its default was used.

Scope: where a variable exists

Variables created inside a function are local: they exist only while that function runs and disappear afterwards. Code inside a function can read variables from outside, but to reassign an outer variable you'd have to declare it global first. Usually it's cleaner to pass values in as arguments and return results.

global scope: the whole scriptLIMIT = 90lives all alonglocal scope: inside check(used)percent = used / 2exists only while it runsif percent > LIMIT:reading LIMIT is finereads outwardpercent is gone after return
Inside a function you can see out, but nothing outside can see in. When the function returns, its local variables are thrown away.

Tracing a loop by hand

When a loop confuses you, play computer: write down each variable after every step. Here's a loop that adds up response times:

times = [120, 80, 200]
total = 0
for t in times:
    total = total + t
print(total)   # 400
Stepttotal after the step
before the loop(none)0
1st time round120120
2nd time round80200
3rd time round200400

Most loops follow one of a few patterns, and recognising them makes code much easier to write:

# count: how many match?
down = 0
for s in statuses:
    if s != "up":
        down += 1

# find: stop at the first match
first_error = None
for line in lines:
    if "ERROR" in line:
        first_error = line
        break

# collect: build a new list
big = []
for f in files:
    if f["size_mb"] > 100:
        big.append(f["name"])

Why functions are worth it

The moment you copy and paste a block of code, it's time for a function. Copied code means every fix has to be made twice, and one copy always gets forgotten. A function also gives the logic a name, so the rest of the script reads like a description of what it does:

def is_valid_port(port):
    return 1 <= port <= 65535

def parse_address(text):
    host, port = text.split(":")       # "db-01:5432" -> "db-01", "5432"
    return host, int(port)             # a function can return several values

host, port = parse_address("db-01:5432")
if not is_valid_port(port):
    print("bad port")

Small functions that each do one job, with clear names, are the main difference between a script that's easy to change and one nobody wants to touch.

Try it yourself

  1. Print the numbers 1 to 20, but print check instead of every multiple of 5.

    Show an answer
    for n in range(1, 21):
        if n % 5 == 0:
            print("check")
        else:
            print(n)
  2. Write a function status(cpu) that returns "critical" above 90, "warning" above 70, and "ok" otherwise.

    Show an answer
    def status(cpu):
        if cpu > 90:
            return "critical"
        if cpu > 70:
            return "warning"
        return "ok"

    Each return ends the function, so no elif is needed.

  3. Use a while loop to count down from 5 to 1, then print go!.

    Show an answer
    n = 5
    while n > 0:
        print(n)
        n -= 1
    print("go!")

Questions

Pick an answer. Get it wrong and you can try again right away, no waiting. 10 questions per topic - pick a filter below, then use Recreate questions for a fresh set on that topic.

Fresh questions every time

Exam

A mixed test across the whole site, shuffled so you never know which topic comes next. When you submit, every mistake comes with the reason and a jump to the exact moment in the video that explains it.

30 questions 6 topics 20 minute limit Up to 70 XP
1–4 answer · ←→ move
History

Essay

0 / 200-250 words
Sample answer
History
0:00 / 0:00
Not started

on YouTube
Subscribe

Topic progress

Activity

Achievements

Settings

Your profile and your account.

Profile details

* Required. Saved in this browser until you sign in.

Letters, numbers, dots, dashes and underscores.
0 / 160

Account

Checking…

App

Install Stackwise on your phone or computer. It opens in its own window from your home screen, and the Docs and cheat sheets you've opened keep working without internet.

Only admins can see this

Dashboard

Sign-ups, activity, messages and reviews in one place.

Prove it

Certificates

Pass a topic's test and get a certificate with its own public page you can share or add to LinkedIn. Each test is 10 questions drawn at random and graded on the server; you need 8 right, you have 15 minutes, and you get one try per topic a day.

From first command to production

Linux for DevOps

A path through Linux the way DevOps engineers use it: ten stages, every command explained with its flags, examples, real output and mistakes, the combinations engineers chain together, and incidents worked through step by step. Practise everything in a safe lab folder.

Before the interview

Interview prep

Questions that come up in real DevOps interviews, with the kind of answer that lands. Say yours out loud first, then compare. Each one links to the chapter that goes deeper.

    Private to you

    My notes

    Everything you wrote down while watching and reading, in one place. Saved to your account, never shown to anyone.