Getting User Input with input()
The problem appears when the user enters hello instead of 98.6.
Try it: try / except / else / finally
How an exception jumps out of a try block to the first matching except clause, when else runs, and why finally always runs.
How it works
- Statements in try run until one raises an exception; the rest of try is skipped.
- Python checks the except clauses in order and runs the first one whose type matches.
- If nothing was raised, the else block runs instead.
- finally runs in every case.
Default run (9 steps): Call safe_divide('4'). … Return 25.0. Output was: Worked: 25.0 / Done.
Simplified: One fixed function; int() and / are modelled exactly (including how Python prints floats), but nothing is executed as Python.
Loading the simulation…
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
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.
- 1Get the input
Call
input()before the try clause and store what the user entered in inp. - 2Attempt conversion
Place
float(inp)inside the try clause because converting non-numeric text can raise aValueError. - 3Continue only after success
Calculate Celsius and print the result inside the try clause. These statements should run only when the conversion succeeds.
- 4Handle failure
Use the except clause to display a friendly message when a
ValueErroroccurs.
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. |
Both versions attempt the same conversion, but their responses to invalid input differ.
Mistakes with Exception Placement
Common mistake Putting the conversion outside the try clause
What it looks liketemperature = float(inp) try: celsius = (temperature - 32) * 5 / 9Why it failsIf
float(inp)raises aValueError, the error occurs before Python reaches the try clause, so this handler cannot handle it.Do this insteadPut float(inp) inside the try clause.
Common mistake Putting the calculation after a failed conversion
What it looks liketry: temperature = float(inp) except ValueError: print("Please enter a number") celsius = (temperature - 32) * 5 / 9Why it failsWhen conversion fails, the calculation should not be attempted. The source example keeps the conversion and dependent calculation in the try clause.
Do this insteadKeep the calculation in the try clause so it runs only after conversion succeeds.
Common mistake Allowing the except clause to be vague or unhelpful
What it looks likeexcept ValueError: print("Error")Why it failsA vague response does not explain what the user should do next.
Do this insteadProvide a clear message such as Please enter a number.
Common mistake Treating invalid input as a successful result
What it looks likeexcept ValueError: print(celsius)Why it failsThe conversion failed, so there is no valid Celsius result to display.
Do this insteadUse 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
ValueErrorclause to print a clear message.
- 1Mark the first operation that can fail.
- 2Place that operation in the try clause.
- 3Keep dependent calculations in the try clause.
- 4Write the user-facing response in the except clause.
- 5Check that invalid input skips the calculation and reaches the handler.
Key Takeaways
- 1The try clause contains code that might fail, such as
float(inp)when handling user input. - 2The except clause runs only when a matching error occurs in the try clause.
- 3If conversion fails, Python skips the remaining statements in the try clause and moves to the except clause.
- 4A clear error message gives the user a useful response instead of a cryptic crash report.
- 5Keep the try clause focused, while including dependent calculations that should run only after successful conversion.
At a glance
- 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.