Concepts / Getting User Input with input()

Getting User Input with input()

The problem appears when the user enters hello instead of 98.6.

  • Programming
Interactive lab

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

  1. Statements in try run until one raises an exception; the rest of try is skipped.
  2. Python checks the except clauses in order and runs the first one whose type matches.
  3. If nothing was raised, the else block runs instead.
  4. 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.

Educational simulation

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.

python
Output
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

User inputhellofloat(inp)inside tryValueErrorexcepthandle the errorError messagePlease enter a numberCelsius calculationpasses toraisesmatching errordisplaysonly if conversion succeeds
What happens after float() cannot convert the user's input?

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?

  • The Celsius calculation

  • The except clause

  • The error message

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

input()get texttryfloat(inp)Celsius calculationexcept ValueErrorFriendly messagePlease enter a numberprovides inpattemptif successfulif ValueErrorresponds with
Which operations are attempted normally, and which operation runs only after a matching error?

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.

Best practice

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

Worked example

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.

  1. 1
    Get the input

    Call input() before the try clause and store what the user entered in inp.

  2. 2
    Attempt conversion

    Place float(inp) inside the try clause because converting non-numeric text can raise a ValueError.

  3. 3
    Continue only after success

    Calculate Celsius and print the result inside the try clause. These statements should run only when the conversion succeeds.

  4. 4
    Handle failure

    Use the except clause to display a friendly message when a ValueError occurs.

Result

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.

python
Output
For input 98.6, the conversion and calculation run, and the Celsius result is printed.

For input hello, the program prints:
Please enter a number

The 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-exceptWith 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 like
    temperature = float(inp)
    try:
        celsius = (temperature - 32) * 5 / 9
    Why it fails

    If float(inp) raises a ValueError, the error occurs before Python reaches the try clause, so this handler cannot handle it.

    Do this instead

    Put float(inp) inside the try clause.

  • Common mistake

    Putting the calculation after a failed conversion

    What it looks like
    try:
        temperature = float(inp)
    except ValueError:
        print("Please enter a number")
    celsius = (temperature - 32) * 5 / 9
    Why it fails

    When conversion fails, the calculation should not be attempted. The source example keeps the conversion and dependent calculation in the try clause.

    Do this instead

    Keep 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 like
    except ValueError:
        print("Error")
    Why it fails

    A vague response does not explain what the user should do next.

    Do this instead

    Provide a clear message such as Please enter a number.

  • Common mistake

    Treating invalid input as a successful result

    What it looks like
    except ValueError:
        print(celsius)
    Why it fails

    The conversion failed, so there is no valid Celsius result to display.

    Do this instead

    Use the except clause to communicate the problem instead of displaying a calculation that could not be completed.

Practice the Control Flow

MEDIUM

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.
  1. 1
    Mark the first operation that can fail.
  2. 2
    Place that operation in the try clause.
  3. 3
    Keep dependent calculations in the try clause.
  4. 4
    Write the user-facing response in the except clause.
  5. 5
    Check that invalid input skips the calculation and reaches the handler.

Key Takeaways

  1. 1
    The try clause contains code that might fail, such as float(inp) when handling user input.
  2. 2
    The except clause runs only when a matching error occurs in the try clause.
  3. 3
    If conversion fails, Python skips the remaining statements in the try clause and moves to the except clause.
  4. 4
    A clear error message gives the user a useful response instead of a cryptic crash report.
  5. 5
    Keep 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.

Related concepts

More concepts starting with G