Type Conversion: Strings, Integers, and Floats
The conversion works when the response represents a number, but invalid text such as hello causes Python to raise a ValueError.
Try it: Type conversion: int(), float(), str(), bool()
Exactly how int(), int(text, base), float(), str() and bool() turn a value into another type: Python's real parsing rules for text (whitespace, sign, underscores, 0x/0o/0b prefixes, inf/nan, exponents) and its truthiness rules.
How it works
- int(text) strips surrounding whitespace, allows one sign, then reads digits (underscores only between digits); any other character raises ValueError: invalid literal for int().
- int(text, base) reads digits in that base; base 0 takes the base from a 0x / 0o / 0b prefix like a Python literal.
- float(text) accepts decimals like '.5', '5.', '1e3' and the names inf, infinity and nan, then rounds to the nearest double.
- int() of a float truncates toward zero; str() gives the printed form (repr digits for floats).
- bool() is truthiness: '', 0, 0.0 and None are False; every non-empty string — even '0' or 'False' — is True.
Default run (8 steps): int(' -0x_1F ', 0): the argument is a str of 10 characters. … int(' -0x_1F ', 0) → -31
Simplified: The argument is a Python literal typed as text (ASCII only; escapes \t \n \r). Unicode digits and bytes arguments are not modelled.
Loading the simulation…
When Conversion Fails
User input commonly arrives as text. A program may then try to convert that text into a number before performing a calculation. For example, a temperature converter can ask for a Fahrenheit value, convert the response to a floating-point number, and calculate Celsius. The conversion works when the response represents a number, but invalid text such as hello causes Python to raise a ValueError. Without error handling, the program stops and displays a crash report instead of helping the user.
A try-except block lets you decide what the program should do when a conversion operation fails. Instead of allowing the program to crash, you can show a clear message to the user.
The Error Path
What do you think happens?
A user enters hello when the program tries to convert the response to a floating-point number. What happens next inside a try-except block?
Reveal answer
Python jumps to the except clause and skips the remaining try statements
The conversion raises a ValueError. Python immediately leaves the try clause and runs the except clause, so later calculations and output statements in the try clause are not executed.
The important change is the direction of control flow. When conversion succeeds, the program can continue to the calculation and its output. When conversion fails, Python does not continue with the remaining statements in the try clause. It jumps to the matching except clause instead. This prevents the calculation from using a value that was never successfully converted.
The try-except Structure
The try clause contains code that might fail. The except clause contains the response that runs only when an error occurs in the try clause. Together, these clauses provide exception handling: a defined response to an error that might otherwise stop the program.
inp = input("Enter a Fahrenheit temperature: ")
try:
fahrenheit = float(inp)
celsius = (fahrenheit - 32) * 5 / 9
print(celsius)
except ValueError:
print("Please enter a number")- 1input collects the user's response as text.
- 2float attempts to convert that text into a floating-point number.
- 3If the conversion succeeds, the calculation and print statement can run.
- 4If float raises
ValueError, Python skips the remaining try statements. - 5The except clause prints a message defined by the programmer.
- The input is collected before the risky conversion.
- The conversion might raise
ValueError. - The calculation remains in the try clause because it depends on successful conversion.
- The result is printed only if conversion and calculation proceed.
- The except clause responds to the conversion error.
Please enter a numberIn this example, the user enters hello. The float operation cannot convert that text into a number, so it raises ValueError. The calculation and print statement inside the try clause are skipped. Control moves to except, which displays a friendly message instead of allowing the program to stop with a cryptic crash report.
Choosing the Clause
Put operations that might raise an exception in the try clause. In the temperature converter, the float conversion is the most obvious risky operation. The calculation also belongs there because it depends on successful conversion. Keep the try clause focused rather than placing unrelated code inside it.
Crash Versus Recovery
inp = input("Enter a Fahrenheit temperature: ")
fahrenheit = float(inp)
print(fahrenheit)Invalid text produces an unhandled ValueError and the program stops.
inp = input("Enter a Fahrenheit temperature: ")
try:
fahrenheit = float(inp)
print(fahrenheit)
except ValueError:
print("Please enter a number")Invalid text transfers control to except, which displays a defined message.
Both versions attempt the same conversion, but their behavior differs when the response is invalid. The version without try-except lets the exception escape, so the program crashes and cannot ask the user to try again or show a message chosen for the situation. The handled version defines what happens after the failure and improves the user's experience.
Mistakes to Avoid
Common mistake Putting the conversion outside the try clause
What it looks likefahrenheit = float(inp) try: celsius = (fahrenheit - 32) * 5 / 9Why it failsIf float raises
ValueError, the exception occurs before Python reaches the try clause, so the except clause cannot handle it.Do this insteadPlace the conversion inside the try clause.
Common mistake Continuing with the calculation after conversion fails
What it looks liketry: fahrenheit = float(inp) celsius = (fahrenheit - 32) * 5 / 9Why it failsWhen conversion fails, Python skips the remaining statements in the try clause. The calculation cannot use a successfully converted value.
Do this insteadKeep dependent calculations in the try clause so they run only after conversion succeeds.
Common mistake Allowing the program to expose only a cryptic crash report
What it looks likefahrenheit = float(inp)Why it failsAn invalid response can stop the program without giving the user a clear next step.
Do this insteadCatch the conversion error and provide a friendly message such as Please enter a number.
Common mistake Making the try clause contain unrelated operations
Why it failsA broad, unfocused try clause makes it harder to identify which operation caused the exception and what the except response is handling.
Do this insteadKeep the try clause focused on operations that might raise the expected exception and on calculations that depend on them.
Practice the Control Flow
Write a short temperature-conversion program that asks for a Fahrenheit value, attempts the floating-point conversion inside a try clause, and prints Please enter a number if the conversion raises ValueError.
Hints
- Collect the input before the try clause.
- Place the conversion and any calculation that depends on it inside the try clause.
- Use an except clause for
ValueError. - The error response should be a clear message for the user.
Tracing an Invalid Response
A temperature converter receives the text hello instead of a numeric temperature. Determine which statements run.
- 1Collect input
The program stores the user's response as text before entering the try clause.
- 2Attempt conversion
float tries to convert hello into a floating-point number and raises
ValueError. - 3Skip dependent statements
Python immediately leaves the try clause, so the calculation and result output do not run.
- 4Handle the exception
Python runs the except clause and displays the user-friendly message selected by the programmer.
The program handles the invalid response with a message instead of continuing to the calculation or stopping with an unhandled crash.
Key Takeaways
- 1Conversion of user input can raise an exception when the text is not suitable for the expected numeric conversion.
- 2The try clause contains code that might fail, while the except clause contains the response to an error.
- 3When an exception occurs, Python skips the remaining statements in the try clause and transfers control to except.
- 4Keeping conversion and dependent calculations inside try prevents the program from continuing without a valid converted value.
- 5Friendly exception handling makes programs more robust and gives users a clearer response than an unhandled crash.
At a glance
- Use try-except to handle conversion errors instead of allowing the program to crash.
- Put risky conversion operations and dependent calculations in the try clause.
- Put the user-friendly response in the except clause.
- When conversion raises an exception, Python skips the rest of try and runs except.