Programming from zero

Swap the active and standby servers

easyFirst steps

Problem statement

During a failover, the standby database becomes active and the old active becomes standby. Start with active = "db-01" and standby = "db-02". Swap the values of the two variables, then print:

Active: db-02 and Standby: db-01 on two lines.

Examples

Example 1

Input: active = "db-01" standby = "db-02"

Output: Active: db-02 Standby: db-01

Hints

Approach

Optimal

A variable holds only one value at a time, so assigning active = standby immediately overwrites the old active server. One fix is a temporary variable: save active in old, then reassign both. Python also has a shortcut called tuple unpacking: active, standby = standby, active. Python first reads both values on the right side, then assigns them to the names on the left, so nothing is lost. Finally, two f-strings print the new state.

Python
active = "db-01"
standby = "db-02"
active, standby = standby, active
print(f"Active: {active}")
print(f"Standby: {standby}")

Follow-up questions

  • Add a third server db-03 and rotate all three: active gets standby, standby gets db-03, db-03 gets the old active.

Frequently asked questions

No, old = active; active = standby; standby = old works fine and is easier to read at first. The one-line swap is just the common Python idiom you will see in other people's code.