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)
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.
Empty comment: len(comment) is zero, so the condition len(comment) == 0 is true. The filename contains only the time and the .zip extension.
Comment with text: len(comment) is not zero, so the other branch runs. replace changes the space to an underscore before the comment is appended.
Directory 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 |
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 selectedStart 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.
Creating a directory without checking whether it already exists.
Repeated runs can attempt to create an existing directory.
Fix:
Use if not os.path.exists(backup_dir): before os.mkdir(backup_dir).Using the unsanitized comment directly in the filename.
The source notes that spaces in filenames can cause problems in many contexts.
Fix:
Replace spaces with underscores before appending the comment.Putting the comment branch outside the conditional structure.
The filename should have one structure when len(comment) is zero and another when it is not.
Fix:
Use if len(comment) == 0 followed by else, with each assignment indented inside its branch.Expecting Python if..elif..else to fall through like a switch with a missing break.
Python chains are mutually exclusive and finish after one branch executes.
Fix:
Put all intended actions in the selected branch; no break statement is needed.Ignoring the status code from os.system.
The script cannot report whether the command succeeded or failed.
Fix:
Store 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")
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.exists returns 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
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
- A reliable backup workflow checks each directory with os.path.exists before calling os.mkdir.
- time.strftime supplies compact date and time strings, while len and replace support conditional filename generation and sanitization.
- Python has no switch statement; if..elif..else is its direct, mutually exclusive alternative.
- Unlike switch fall-through, a Python conditional chain ends after one branch executes.
- Dictionary dispatch maps keys directly to functions or values and is useful for larger or more dynamic branching systems.
Key Takeaways
- 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.