
"If you're using print calls to debug your Python code, consider using f-strings with self-documenting expressions instead. A broken Python program Here we have a program that makes a random math prompt and then validates whether the answer give by the user is correct: This program doesn't work right now: $ python3 check_mult.py What's 9 multiplied by 8? 72 That's incorrect Our program always tells us that our answer is incorrect."
"Now, we could try to debug this code by adding some print calls, which will print out what our answer is and what the expected answer is: But the answer and the expected answer look the same right now: $ python3 check_mult.py What's 5 multiplied by 1? 5 answer: 5 expected: 5 That's incorrect Both the answer and the expected answer seem to be 5."
A small Python program generates a random multiplication prompt and checks whether the user's input matches the expected numeric result. The program incorrectly reports answers as incorrect because the user's response remains a string with surrounding whitespace. Simple print debugging shows identical human-readable values, masking the type mismatch. Using f-strings with self-documenting expressions and the = marker prints both variable names and their programmer-readable representations (repr), revealing that answer is a string while expected is an integer. Converting the answer string to a numeric type fixes the validation so comparisons use matching types.
Read at Pythonmorsels
Unable to calculate read time
Collection
[
|
...
]