Type Conversion: Strings, Integers, and Floats
try-except blocks allow programs to catch and handle errors gracefully instead of crashing when unexpected situations occur.
When Conversion Fails
User input commonly arrives as text. A program may then try to convert that text into a number before performing a calculation. For example, a temperature converter can ask for a Fahrenheit value, convert the response to a floating-point number, and calculate Celsius. The conversion works when the response represents a number, but invalid text such as hello causes Python to raise a ValueError. Without error handling, the program stops and displays a crash report instead of helping the user.
A try-except block lets you decide what the program should do when a conversion operation fails. Instead of allowing the program to crash, you can show a clear message to the user.
The Error Path
What do you think happens?
A user enters hello when the program tries to convert the response to a floating-point number. What happens next inside a try-except block?
Reveal answer
Answer: Python jumps to the except clause and skips the remaining try statements
The conversion raises a ValueError. Python immediately leaves the try clause and runs the except clause, so later calculations and output statements in the try clause are not executed.
The important change is the direction of control flow. When conversion succeeds, the program can continue to the calculation and its output. When conversion fails, Python does not continue with the remaining statements in the try clause. It jumps to the matching except clause instead. This prevents the calculation from using a value that was never successfully converted.
The try-except Structure
The try clause contains code that might fail. The except clause contains the response that runs only when an error occurs in the try clause. Together, these clauses provide exception handling: a defined response to an error that might otherwise stop the program.
inp = input("Enter a Fahrenheit temperature: ") try: fahrenheit = float(inp) celsius = (fahrenheit - 32) * 5 / 9 print(celsius) except ValueError: print("Please enter a number")
Please enter a numberIn this example, the user enters hello. The float operation cannot convert that text into a number, so it raises ValueError. The calculation and print statement inside the try clause are skipped. Control moves to except, which displays a friendly message instead of allowing the program to stop with a cryptic crash report.
Choosing the Clause
Put operations that might raise an exception in the try clause. In the temperature converter, the float conversion is the most obvious risky operation. The calculation also belongs there because it depends on successful conversion. Keep the try clause focused rather than placing unrelated code inside it.
Crash Versus Recovery
Both versions attempt the same conversion, but their behavior differs when the response is invalid. The version without try-except lets the exception escape, so the program crashes and cannot ask the user to try again or show a message chosen for the situation. The handled version defines what happens after the failure and improves the user's experience.
Mistakes to Avoid
Putting the conversion outside the try clause
If float raises ValueError, the exception occurs before Python reaches the try clause, so the except clause cannot handle it.
Fix:
Place the conversion inside the try clause.Continuing with the calculation after conversion fails
When conversion fails, Python skips the remaining statements in the try clause. The calculation cannot use a successfully converted value.
Fix:
Keep dependent calculations in the try clause so they run only after conversion succeeds.Allowing the program to expose only a cryptic crash report
An invalid response can stop the program without giving the user a clear next step.
Fix:
Catch the conversion error and provide a friendly message such as Please enter a number.Making the try clause contain unrelated operations
A broad, unfocused try clause makes it harder to identify which operation caused the exception and what the except response is handling.
Fix:
Keep the try clause focused on operations that might raise the expected exception and on calculations that depend on them.
Practice the Control Flow
Write a short temperature-conversion program that asks for a Fahrenheit value, attempts the floating-point conversion inside a try clause, and prints Please enter a number if the conversion raises ValueError.
Hints
- Collect the input before the try clause.
- Place the conversion and any calculation that depends on it inside the try clause.
- Use an except clause for ValueError.
- The error response should be a clear message for the user.
Tracing an Invalid Response
A temperature converter receives the text hello instead of a numeric temperature. Determine which statements run.
Collect input: The program stores the user's response as text before entering the try clause.
Attempt conversion: float tries to convert hello into a floating-point number and raises ValueError.
Skip dependent statements: Python immediately leaves the try clause, so the calculation and result output do not run.
Handle the exception: Python runs the except clause and displays the user-friendly message selected by the programmer.
The program handles the invalid response with a message instead of continuing to the calculation or stopping with an unhandled crash.
Key Takeaways
- Conversion of user input can raise an exception when the text is not suitable for the expected numeric conversion.
- The try clause contains code that might fail, while the except clause contains the response to an error.
- When an exception occurs, Python skips the remaining statements in the try clause and transfers control to except.
- Keeping conversion and dependent calculations inside try prevents the program from continuing without a valid converted value.
- Friendly exception handling makes programs more robust and gives users a clearer response than an unhandled crash.
Key Takeaways
- Use try-except to handle conversion errors instead of allowing the program to crash.
- Put risky conversion operations and dependent calculations in the try clause.
- Put the user-friendly response in the except clause.
- When conversion raises an exception, Python skips the rest of try and runs except.