Concepts / Handling Errors with try and except

Handling Errors with try and except

If int() raises ValueError, the except ValueError block provides a separate response instead of leaving the conversion error unaddressed.

  • 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…

The Value Behind User Input

When a program asks a user to type a number, the value returned by input() is still text. If the user types 42, Python receives the string '42', not the integer 42. This distinction matters whenever the program needs to perform arithmetic.

input()returns text'42'string42integeruser types 42
What type of value does input() produce, and how is that different from the integer needed for arithmetic?
Key point

The characters in the string '10' can be joined or repeated. The integer 10 can be used in arithmetic. They may look similar when displayed, but they are different kinds of values.

Converting Text into an Integer

The int() function converts a string of digits into an integer. Its basic form is int(string_value). You can also place input() directly inside int(), using int(input(...)). This combines receiving the user's text with converting it before storing the result.

17typed by user'17'string from input()int()conversion17integer resultinput() returnspasses textproduces
How does a numeric string returned by input() pass through int() and become an integer?
python
Output
If the user types 17, speed_text contains the string '17'. After int(speed_text), speed contains the integer 17, so the printed result is 20.

Valid Conversions

What do you think happens?

What integer does int() produce in each case?

  • int('7') produces 7 and int('-3') produces -3

  • Both calls produce strings

  • Both calls raise ValueError

Reveal answer
Answer:

int('7') produces the integer 7, and int('-3') produces the integer -3.

int() successfully converts strings containing digits. A leading minus sign is also allowed for a negative integer.

Worked example

Converting a speed value

A user types 17 when asked for a speed. What happens as the value moves through input() and int()?

  1. 1
    Receive the response

    input() returns the user's response as the string '17'.

  2. 2
    Convert the response

    int('17') converts that string into the integer 17.

  3. 3
    Use the result

    The integer 17 can now be used in arithmetic operations.

Result

The converted value is the integer 17, not the string '17'.

python
Output
If the user types 20, the conversion produces the integer 20 and the program prints 21.

When Conversion Fails

int() cannot convert every string. A value such as 'hello' contains non-numeric characters, and a value such as '12.5' represents a decimal rather than an integer string. When int() receives either kind of unsuitable text, it raises a ValueError.

input()returns user textint(text)inside trynumeric textconversion succeedsintegercontinue with valueValueErrorconversion failsexcept ValueErroralternate responseerror messageprogram respondspasses textchecks conversionyesnocaught byresponds with
What happens to program control when int() receives non-numeric input, and how can try and except provide an alternate path?
python

The conversion is placed in the try block. If the entered text can be converted, the program can use the resulting integer. If int() raises ValueError, the except ValueError block provides a separate response instead of leaving the conversion error unaddressed. The important part is that try and except do not make non-numeric text into an integer; they provide a way to manage the failed conversion.

Mistakes Beginners Make

  • Common mistake

    Assuming that input() returns an integer when the user types digits.

    What it looks like
    value = input("Enter a number: ")
    print(value + 2)
    Why it fails

    The response is still a string. String operations do not behave like integer arithmetic.

    Do this instead

    Convert the response before arithmetic: value = int(input("Enter a number: "))

  • Common mistake

    Converting only some numeric inputs.

    What it looks like
    first = int(input("First number: "))
    second = input("Second number: ")
    print(first + second)
    Why it fails

    The second response remains a string, so the values are not both integers.

    Do this instead

    Apply int() to every input that must be used as a whole number.

  • Common mistake

    Expecting int() to accept decimal text.

    What it looks like
    amount = int("12.5")
    Why it fails

    The string contains a decimal point, so it is not a valid integer string for int().

    Do this instead

    Use int() only when the expected input is a whole-number string; recognize that '12.5' causes ValueError.

  • Common mistake

    Treating try and except as a conversion step.

    What it looks like
    try:
        value = input("Enter a number: ")
    except ValueError:
        print("Invalid")
    Why it fails

    The example does not place int() around the input, so it does not attempt the conversion that can raise ValueError.

    Do this instead

    Put the conversion inside try: value = int(input("Enter a number: "))

ExpressionValue kindResult
'10' + '10'Strings'1010' because the strings are joined
10 + 10Integers20 because arithmetic is performed
'10' * 3String and integer'101010' because the string is repeated
10 * 3Integers30 because the integer is multiplied

The same visible digits can participate in different operations depending on whether they are stored as text or as an integer.

Practice the Control Path

MEDIUM

Write a program that asks for a whole number, converts the response with int(), and prints the number multiplied by 3. Put the conversion inside try and use except ValueError to print a clear message when the user enters text such as hello.

Hints
  • input() supplies the initial response as a string.
  • The conversion expression is int(input(...)).
  • The potentially failing conversion belongs inside try.
  • The except clause should handle ValueError.

What do you think happens?

Before running the program, predict what happens when the user enters 'hello' in the try and except example.

  • int() produces an integer

  • int() raises ValueError and the except block prints its message

  • input() automatically changes 'hello' into zero

Reveal answer
Answer:

int('hello') raises ValueError, so the except ValueError block runs and prints the alternate message.

input() returns text, and 'hello' is not a numeric string that int() can convert.

Reliable Numeric Input

  1. 1
    input() always returns the user's response as a string, even when the user types digits.
  2. 2
    Use int(string_value) or int(input(...)) to convert valid whole-number text into an integer.
  3. 3
    A string such as '17' becomes the integer 17, while a string such as 'hello' or '12.5' causes ValueError when passed to int().
  4. 4
    try and except can place the conversion on a protected path and provide an alternate response when ValueError occurs.
  5. 5
    Convert user input before using it in arithmetic, because strings and integers behave differently.

Key Takeaways

  • input() returns text, not an integer.
  • int() converts a string of digits, with an optional leading minus sign, into an integer.
  • Invalid text such as 'hello' and '12.5' causes int() to raise ValueError.
  • A try and except structure can manage that failed conversion and give the user a separate response.
  • Converting input is essential before performing arithmetic.

Related concepts

More concepts starting with H