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.
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…
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.
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.
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?
Reveal 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.
Converting a speed value
A user types 17 when asked for a speed. What happens as the value moves through input() and int()?
- 1Receive the response
input()returns the user's response as the string '17'. - 2Convert the response
int('17')converts that string into the integer 17. - 3Use the result
The integer 17 can now be used in arithmetic operations.
The converted value is the integer 17, not the string '17'.
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.
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 likevalue = input("Enter a number: ") print(value + 2)Why it failsThe response is still a string. String operations do not behave like integer arithmetic.
Do this insteadConvert the response before arithmetic: value = int(input("Enter a number: "))
Common mistake Converting only some numeric inputs.
What it looks likefirst = int(input("First number: ")) second = input("Second number: ") print(first + second)Why it failsThe second response remains a string, so the values are not both integers.
Do this insteadApply int() to every input that must be used as a whole number.
Common mistake Expecting int() to accept decimal text.
What it looks likeamount = int("12.5")Why it failsThe string contains a decimal point, so it is not a valid integer string for
int().Do this insteadUse 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 liketry: value = input("Enter a number: ") except ValueError: print("Invalid")Why it failsThe example does not place
int()around the input, so it does not attempt the conversion that can raiseValueError.Do this insteadPut the conversion inside try: value = int(input("Enter a number: "))
| Expression | Value kind | Result |
|---|---|---|
| '10' + '10' | Strings | '1010' because the strings are joined |
| 10 + 10 | Integers | 20 because arithmetic is performed |
| '10' * 3 | String and integer | '101010' because the string is repeated |
| 10 * 3 | Integers | 30 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
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.
Reveal 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
input()always returns the user's response as a string, even when the user types digits. - 2Use
int(string_value)orint(input(...))to convert valid whole-number text into an integer. - 3A string such as '17' becomes the integer 17, while a string such as 'hello' or '12.5' causes
ValueErrorwhen passed toint(). - 4try and except can place the conversion on a protected path and provide an alternate response when
ValueErroroccurs. - 5Convert 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 raiseValueError. - A try and except structure can manage that failed conversion and give the user a separate response.
- Converting input is essential before performing arithmetic.