Let’s break this down step by step:
1️⃣ try:
-
This starts a try block — Python will run the code inside it, but if an error occurs, it will jump to the matching except block.
2️⃣ d = {"a": 1}
-
Creates a dictionary d with one key-value pair:
-
Key: "a"
-
Value: 1
-
So d looks like:
3️⃣ print(d["b"])
-
This tries to access the value for the key "b".
-
Since "b" is not present in the dictionary, Python raises a KeyError.
4️⃣ except KeyError:
-
This block catches errors of type KeyError.
-
Because the error matches, Python runs the code inside this block instead of stopping the program.
5️⃣ print("Key missing")
-
Prints the message "Key missing" to tell the user that the requested key doesn’t exist.
✅ Final Output:


0 Comments:
Post a Comment