Concepts / Conditional Logic in Python

Conditional Logic in Python

Python has no switch statement; this is a deliberate design choice, not an oversight.

  • Programming

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.

organizeplace insidecombine path and nameinsert targetexecuteSource filesMain backup directorycheck, then create ifmissingDate subdirectorycurrent dateBackup filenametime plus optional commentZip commandtarget path plus sourcefilesStatus codezero means success
What happens next as the script prepares directories, builds a filename, and runs the backup 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)

TrueFalsenot reverses resultos.path.existsdirectory pathDirectory existsskip os.mkdirDirectory missingnot exists is trueos.mkdircreate directory
How does the script decide whether to create each directory?

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.

python
Output (expected)
20240115
143025_evening_files.zip
replace spaces with underscorescombine with time and extensionevening filesuser comment143025current time143025_evening_files.zipsanitized backup filename
How does the original comment become part of a filename with spaces replaced by underscores?

Tracing 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.

python
Output (expected)
run backup
TrueFalseTrueFalseoperation is backupfirst conditionBackup actionfirst matching branchoperation is restorechecked only if neededRestore actionsecond matching branchDefault actionno condition matched
How does control flow move through an if..elif..else chain, and why is only one matching branch executed?

From Switch Cases to Python

Decision featureC or C++ switchPython if..elif..else
Branch selectionCases compare against a switch expressionConditions are checked in order
Default behaviordefault handles unmatched caseselse handles unmatched conditions
Multiple branch executionCan fall through when break is omittedOnly one branch executes
Stopping a branchbreak is commonly used to prevent fall-throughNo break is needed for the chain
selectselect oneC or C++ switchcase may continue withoutbreakPythonif..elif..elseconditions are mutuallyexclusiveMatching casefall-through possibleOne matching branchchain exits after execution
What is the difference between automatic fall-through in a C or C++ switch and Python's explicit branch selection?
python
Output (expected)
second case

This 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.

python
Output (expected)
backup selected
lookupreturnscallbackupoperation keyactionsdictionarymake_backupmapped functionbackup selectedfunction result
How does an input key map directly to the function or action that should be executed?

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.

  • 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

MEDIUM

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?

  • The current time followed by .zip
  • The current time followed by an underscore and the comment
  • The date followed by the unmodified empty comment
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

  1. A reliable backup workflow checks each directory with os.path.exists before calling os.mkdir.
  2. time.strftime supplies compact date and time strings, while len and replace support conditional filename generation and sanitization.
  3. Python has no switch statement; if..elif..else is its direct, mutually exclusive alternative.
  4. Unlike switch fall-through, a Python conditional chain ends after one branch executes.
  5. 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.