Sub topic 2
Handling Bad Input and Formatting Values
Assume you know variables, str, int, float, if, while, and basic try/except. This chapter shows how to recover from invalid input and present values clearly.
Handling bad input with `try`/`except` and retry loops
input() always returns a string. Converting that string can raise ValueError when its contents are not a valid number. Put the conversion inside try, handle the error in except, and repeat with a loop.
while True:
raw = input("Age: ")
try:
age = int(raw)
except ValueError:
print(f"{raw!r} is not a whole number.")
else:
break
print(f"Next year you will be {age + 1}.")The else block runs only when the conversion succeeds. The break then ends the retry loop.
`str()` for people, `repr()` for programmers
str(value) gives a readable form for users. repr(value) gives an unambiguous representation useful for debugging. It often includes quotes and visible escape sequences.
text = "tab\there"
print(str(text))
print(repr(text))The first output contains a tab. The second displays the escape sequence, making hidden characters easier to find.
Formatting with f-strings
An f-string is a string prefixed with f that evaluates expressions inside braces.
name = "Ada"
score = 93.456
print(f"{name} scored {score:.1f}")
print(f"{score = }")The first line prints one decimal place. The = specifier prints the expression and its value, which helps with quick debugging.
Width, alignment, precision, and number formats
A format specification follows a colon inside braces. Width controls space, < aligns left, > aligns right, ,.2f adds thousands separators and two decimal places, and .1% displays a percentage.
price = 1234.5
print(f"{'Item':<10}{'Total':>12}")
print(f"{'Widget':<10}{price:>12,.2f}")
print(f"{0.256:.1%}")Exercise
What exception should a retry loop catch when int(raw) receives "12.5"?
Show answer
ValueError, because the text is not a valid integer.