Getting User Input with input()
try-except blocks allow programs to catch and handle errors gracefully instead of crashing when unexpected situations occur.
When Input Goes Wrong
A program that asks for a temperature seems simple: get the user's input, convert it to a number, calculate Celsius, and display the result. The problem appears when the user enters hello instead of 98.6. The float() function cannot convert that text to a number, so Python raises a ValueError and the program stops. A try-except block lets you decide what the program should do instead of allowing this unexpected situation to produce a crash.
If the user enters hello, float(inp) raises a ValueError. The calculation and print statement are not completed, and the program stops.The Error-Control Path
A try-except block has two important parts. The try clause contains code that might fail. Python attempts that code first. The except clause contains the response for an error that occurs in the try clause. If the conversion raises a ValueError, Python moves to the except clause rather than continuing with the remaining statements in the try clause. If no error occurs, the except clause is skipped.
What do you think happens?
If the user enters hello, which line will not run after float(inp) raises a ValueError?
Reveal answer
Answer: The Celsius calculation will not run. Python immediately moves from the failed conversion to the matching except clause.
The calculation depends on a successful conversion. When the conversion fails, Python skips the remaining code in the try clause and executes the except clause.
Placing Code in try and except
Use the try clause for operations that might raise an exception. In this example, float(inp) is the main risky operation because non-numeric input can cause a ValueError. The calculation can also remain in the try clause because it depends on the conversion succeeding. If conversion fails, there is no useful reason to continue to the calculation. The except clause should contain the response to the error, such as displaying a clear message.
Keep the try clause focused on operations that might fail. The source material notes that input() itself is unlikely to raise an exception in this context, so it can be placed before the try clause. This separates obtaining the input from converting and using it.
A Safe Temperature Conversion
Handling a non-numeric temperature
Write a Fahrenheit-to-Celsius conversion that responds clearly when the user enters text that cannot be converted to a number.
Get the input: Call input() before the try clause and store what the user entered in inp.
Attempt conversion: Place float(inp) inside the try clause because converting non-numeric text can raise a ValueError.
Continue only after success: Calculate Celsius and print the result inside the try clause. These statements should run only when the conversion succeeds.
Handle failure: Use the except clause to display a friendly message when a ValueError occurs.
The program calculates and displays Celsius for convertible input. For input such as hello, it displays Please enter a number instead of stopping with a crash.
For input 98.6, the conversion and calculation run, and the Celsius result is printed.
For input hello, the program prints:
Please enter a numberThe important control-flow detail is that an error does not merely add a message before the calculation. When float(inp) raises a ValueError, Python immediately leaves the remaining statements in the try clause and enters the except clause. The calculation and result display are skipped for that attempt.
What the Handler Changes
| Without try-except | With try-except |
|---|---|
| Invalid input causes a ValueError. | Invalid input causes a ValueError that the except clause handles. |
| The program crashes and stops. | The program displays a message chosen by the programmer. |
| The user sees a cryptic crash report. | The user receives a clearer response such as Please enter a number. |
Mistakes with Exception Placement
Putting the conversion outside the try clause
If float(inp) raises a ValueError, the error occurs before Python reaches the try clause, so this handler cannot handle it.
Fix:
Put float(inp) inside the try clause.Putting the calculation after a failed conversion
When conversion fails, the calculation should not be attempted. The source example keeps the conversion and dependent calculation in the try clause.
Fix:
Keep the calculation in the try clause so it runs only after conversion succeeds.Allowing the except clause to be vague or unhelpful
A vague response does not explain what the user should do next.
Fix:
Provide a clear message such as Please enter a number.Treating invalid input as a successful result
The conversion failed, so there is no valid Celsius result to display.
Fix:
Use the except clause to communicate the problem instead of displaying a calculation that could not be completed.
Practice the Control Flow
Write a short Python program that asks for a Fahrenheit temperature, converts the input with float(), and prints a friendly message if the input causes a ValueError. Before running it, trace what happens for a numeric input and for the input hello.
Hints
- Place input() before the try clause.
- Put float(inp) and the calculation in the try clause.
- Use an except ValueError clause to print a clear message.
- Mark the first operation that can fail.
- Place that operation in the try clause.
- Keep dependent calculations in the try clause.
- Write the user-facing response in the except clause.
- Check that invalid input skips the calculation and reaches the handler.
Key Takeaways
- The try clause contains code that might fail, such as float(inp) when handling user input.
- The except clause runs only when a matching error occurs in the try clause.
- If conversion fails, Python skips the remaining statements in the try clause and moves to the except clause.
- A clear error message gives the user a useful response instead of a cryptic crash report.
- Keep the try clause focused, while including dependent calculations that should run only after successful conversion.
Key Takeaways
- Use try-except to handle runtime errors gracefully instead of letting the program crash.
- Place risky operations such as float() inside the try clause.
- When an exception occurs, Python skips the remaining try statements and runs the matching except clause.
- Use the except clause to provide a clear, user-friendly message.
- Keep dependent calculations in the try clause so they run only after successful input conversion.