Handling Errors with try and except
The input() function returns a string, so you must use int() to convert it to an integer for arithmetic operations.
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
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()?
Receive the response: input() returns the user's response as the string '17'.
Convert the response: int('17') converts that string into the integer 17.
Use 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
Assuming that input() returns an integer when the user types digits.
The response is still a string. String operations do not behave like integer arithmetic.
Fix:
Convert the response before arithmetic: value = int(input("Enter a number: "))Converting only some numeric inputs.
The second response remains a string, so the values are not both integers.
Fix:
Apply int() to every input that must be used as a whole number.Expecting int() to accept decimal text.
The string contains a decimal point, so it is not a valid integer string for int().
Fix:
Use int() only when the expected input is a whole-number string; recognize that '12.5' causes ValueError.Treating try and except as a conversion step.
The example does not place int() around the input, so it does not attempt the conversion that can raise ValueError.
Fix:
Put 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 |
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
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
- input() always returns the user's response as a string, even when the user types digits.
- Use int(string_value) or int(input(...)) to convert valid whole-number text into an integer.
- A string such as '17' becomes the integer 17, while a string such as 'hello' or '12.5' causes ValueError when passed to int().
- try and except can place the conversion on a protected path and provide an alternate response when ValueError occurs.
- 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.