Skip to main content
Programming from zero

Swap the active and standby servers

easyFirst steps

Problem statement

A failover just happened: the standby server needs to become active, and the active one becomes standby. You have two variables holding their names, and you need to swap what's stored in them.

flowchart LR A["temp = active"] --> B["active = standby"] --> C["standby = temp"] classDef save fill:#DBEAFE,stroke:#2563EB,color:#1E3A8A classDef overwrite fill:#FEF3C7,stroke:#D97706,color:#92400E classDef restore fill:#D1FAE5,stroke:#059669,color:#065F46 class A save class B overwrite class C restore

Common mistake: swapping without a temporary variable overwrites the original value before you can save it.

TEXT
Wrong:
active = standby
standby = active

The first line already replaces active's original value. By the time the second line runs, both variables end up holding standby's original value - the original active is gone. That's exactly why temp exists: it holds active's original value safely while the other two lines overwrite everything else.

Your task: start with active = "srv-a" and standby = "srv-b". Swap the two values, then print them in the form active: <name>, standby: <name>.

Expected output:

TEXT
active: srv-b, standby: srv-a

Approach

The everyday way to swap two variables needs a third, temporary variable to hold one value while you overwrite it - otherwise the first assignment overwrites a value you still need for the second one:

  1. Copy active into a temporary variable, temp.
  2. Copy standby into active.
  3. Copy temp (the original active) into standby.

This three-step version works in every language, so learn it first. All three tabs below use it.

Python-only shortcut: Python can also swap in one line, active, standby = standby, active. Java and C++ have no equivalent, so don't expect it to work there. (If you're curious how that line works, see tuple unpacking in the Python docs. You'll meet the idea properly later in this track.)

active = "srv-a"
standby = "srv-b"

temp = active
active = standby
standby = temp

print(f"active: {active}, standby: {standby}")