Python Conditional del
Delete a locker mapping only after checking its current owner.
A simple example
Conditional del
- Start with A = 1
- Do this Remove A if its value is 1
- Result A is absent
Syntax
del claims[key]
Run these examples in Python
Save one example at a time as lesson.py. Use Python 3.9 or later.
python3 lesson.pyRelease a locker only for its recorded owner
A school uses locker numbers as keys and student names as values. When Mira returns her locker, the desk clears the assignment only if the current register still names Mira.
claims = {"L2": "Mira"}
if claims.get("L2") == "Mira":
del claims["L2"]
print("Released")
Released
The matching owner permits removal of locker L2.
Return a locker key
A locker has a single claim and its registered holder returns the key. The clerk removes the claim only when the recorded owner matches the claimant. How many claims remain?
Keep a reserved headset
A different student tries to release the only headset claim. The clerk removes the claim only when the recorded owner matches the claimant. How many claims remain?
What to watch for
Deleting an absent key raises KeyError. Keep the ownership check close to the deletion.