Conditional Logic in Python
Python has no switch statement; this is a deliberate design choice, not an oversight.
Following the Backup Workflow
Conditional logic becomes easier to understand when you follow the values moving through a complete task. A file backup workflow combines directory management, date and time formatting, string manipulation, and a decision about whether the user supplied a comment. The workflow first prepares a main backup directory, then prepares a date-based subdirectory, then creates a filename from the current time and optional comment, and finally constructs and executes a zip command.
The important habit is to trace one decision at a time. Directory existence decisions control whether os.mkdir runs. Comment length controls which filename branch runs. The result of os.system controls whether the script reports success or failure.
Preparing Directories Safely
The backup script creates a two-level directory structure. It checks the main backup directory first. If os.path.exists reports that the directory does not exist, the not operator reverses the result and the condition becomes true, so os.mkdir creates the directory. The same pattern is then used for a date-based subdirectory inside the main directory. Checking before creating allows the script to run repeatedly without attempting to create a directory that is already present.
import os
backup_dir = "backups"
date_dir = backup_dir + os.sep + "20240115"
if not os.path.exists(backup_dir):
os.mkdir(backup_dir)
if not os.path.exists(date_dir):
os.mkdir(date_dir)
print(date_dir)- 1Import os so the script can use path checks, directory creation, and the operating-system path separator.
- 2Set the main backup directory name.
- 3Build the date-based subdirectory path with
os.sep. - 4Create the main directory only when
os.path.existssays it is missing. - 5Create the date-based subdirectory only when it is missing.
- 6Print the path so the execution can be traced.
Building a Dynamic Filename
The filename uses the current time and an optional user comment. time.strftime formats the current date and time. The format string %Y%m%d produces a date with no separators, while %H%M%S produces a time with no separators. The date is used for the subdirectory, and the time and optional comment form the filename.
20240115
143025_evening_files.zipTracing Empty and Nonempty Comments
Determine which filename branch runs when the comment is empty and when it contains the text morning files.
- 1Empty comment
len(comment)is zero, so the conditionlen(comment)== 0 is true. The filename contains only the time and the .zip extension. - 2Comment with text
len(comment)is not zero, so the other branch runs. replace changes the space to an underscore before the comment is appended. - 3Directory placement
The date string identifies the date-based subdirectory, while the generated filename identifies the backup inside that directory.
The two cases produce different filenames because conditional logic selects the filename structure according to the comment length.
Choosing One Branch with If Chains
Python has no switch statement. This is a deliberate design choice rather than an oversight. The direct replacement for a C or C++ switch is an if..elif..else chain: each elif corresponds to another case, and else corresponds to the default case. Python evaluates the conditions in order. Once one branch executes, the entire chain is finished, so the branches are mutually exclusive and there is no fall-through.
run backupFrom Switch Cases to Python
| Decision feature | C or C++ switch | Python if..elif..else |
|---|---|---|
| Branch selection | Cases compare against a switch expression | Conditions are checked in order |
| Default behavior | default handles unmatched cases | else handles unmatched conditions |
| Multiple branch execution | Can fall through when break is omitted | Only one branch executes |
| Stopping a branch | break is commonly used to prevent fall-through | No break is needed for the chain |
The source describes if..elif..else as the direct, mutually exclusive replacement for switch logic.
second caseThis translation preserves the central decision: compare one value with several alternatives and select the matching action. The Python version makes the end of each alternative explicit through indentation and the structure of the chain, rather than relying on break statements to prevent later cases from running.
Scaling Branches with Dictionary Dispatch
An if..elif..else chain is the recommended starting point because it is clear, straightforward, and requires no setup. When there are many branches, or when operation names should map directly to functions, dictionary dispatch can make the decision logic more modular. A dictionary maps keys such as strings or integers to functions or values. Looking up a key returns the corresponding function, which can then be called.
backup selected- The dictionary associates each operation name with a function.
- The lookup returns the function associated with the operation key.
- The parentheses call the returned function.
Start with if..elif..else for most decisions. Consider dictionary dispatch when you have more than five or six elif branches, when simple values map directly to choices, or when functions should be selected dynamically. Dictionary dispatch separates the decision about which function to call from the execution performed by that function.
Debugging Branch and Syntax Problems
A multi-step automation script is easiest to debug when each stage exposes its values. Print the directory paths, the generated filename, and the zip command before execution. Then inspect the status code returned by os.system: zero indicates success, while any other value indicates failure. Testing several inputs, including an empty comment and a comment containing spaces, helps verify that both filename branches work.
Common mistake Creating a directory without checking whether it already exists.
What it looks likeos.mkdir(backup_dir) runs every time the script starts.
Why it failsRepeated runs can attempt to create an existing directory.
Do this insteadUse if not os.path.exists(backup_dir): before os.mkdir(backup_dir).Common mistake Using the unsanitized comment directly in the filename.
What it looks likefilename = current_time + "_" + comment + ".zip"Why it failsThe source notes that spaces in filenames can cause problems in many contexts.
Do this insteadReplace spaces with underscores before appending the comment.
Common mistake Putting the comment branch outside the conditional structure.
What it looks likeBoth the empty-comment and nonempty-comment filename statements execute as ordinary sequential statements.
Why it failsThe filename should have one structure when
len(comment)is zero and another when it is not.Do this insteadUse if len(comment) == 0 followed by else, with each assignment indented inside its branch.
Common mistake Expecting Python if..elif..else to fall through like a switch with a missing break.
What it looks likeA matching branch executes and the learner expects the following branch to execute too.
Why it failsPython chains are mutually exclusive and finish after one branch executes.
Do this insteadPut all intended actions in the selected branch; no break statement is needed.
Common mistake Ignoring the status code from os.system.
What it looks likeos.system(command) runs, but the script never checks the returned value.
Why it failsThe script cannot report whether the command succeeded or failed.
Do this insteadStore the return value and treat zero as success and any other value as failure.
import os
import time
backup_dir = "backups"
date_name = time.strftime("%Y%m%d")
date_dir = backup_dir + os.sep + date_name
comment = "weekly files"
if not os.path.exists(backup_dir):
os.mkdir(backup_dir)
if not os.path.exists(date_dir):
os.mkdir(date_dir)
current_time = time.strftime("%H%M%S")
if len(comment) == 0:
filename = current_time + ".zip"
else:
comment = comment.replace(" ", "_")
filename = current_time + "_" + comment + ".zip"
target = date_dir + os.sep + filename
source = ["notes.txt", "report.txt"]
command = "zip {} {}".format(target, " ".join(source))
print(date_dir)
print(filename)
print(command)
status = os.system(command)
if status == 0:
print("backup succeeded")
else:
print("backup failed")- 1The os and time modules provide the directory, path, date, and time operations used by the workflow.
- 2The date string becomes part of the subdirectory path.
- 3Each directory is checked before
os.mkdiris called. - 4The comment is tested with len and sanitized with replace when it is nonempty.
- 5The target path combines the date directory and generated filename.
- 6join places spaces between source paths for the zip command.
- 7format inserts the target and source text into the command template.
- 8The command is printed before execution so the generated values can be inspected.
- 9The returned status code is checked after
os.systemfinishes.
Practice the Decision Trace
Trace this generated scenario without running it. The main backup directory already exists, the date-based subdirectory does not exist, and the user enters the comment "project notes". Identify which os.mkdir call runs, which filename branch runs, what the sanitized comment becomes, and whether the if..elif..else rule would allow a second branch to run after the first match.
Hints
- For each directory, ask what
os.path.existsreturns before applying not. - Compare the comment length with zero.
- Apply replace to the space before constructing the filename.
- Remember that one matching if..elif..else branch ends the chain.
What do you think happens?
The comment is empty. Which filename form does the backup workflow select?
Reveal answer
The current time followed by .zip
When len(comment) is zero, the empty-comment branch creates a filename containing only the time and the .zip extension.
Key Takeaways
- 1A reliable backup workflow checks each directory with
os.path.existsbefore callingos.mkdir. - 2
time.strftimesupplies compact date and time strings, while len and replace support conditional filename generation and sanitization. - 3Python has no switch statement; if..elif..else is its direct, mutually exclusive alternative.
- 4Unlike switch fall-through, a Python conditional chain ends after one branch executes.
- 5Dictionary dispatch maps keys directly to functions or values and is useful for larger or more dynamic branching systems.
At a glance
- Conditional logic controls directory creation, filename selection, and operation selection in Python automation.
- Check paths before creating directories, sanitize comments before using them in filenames, and print intermediate values while debugging.
- Use if..elif..else as the clear replacement for C or C++ switch logic because Python branches do not fall through.
- Use dictionary dispatch when many keys should map directly to functions or values.