Concepts / Type Conversion: Strings, Integers, and Floats

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.

  • Programming
Interactive lab

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

  1. int(text) strips surrounding whitespace, allows one sign, then reads digits (underscores only between digits); any other character raises ValueError: invalid literal for int().
  2. int(text, base) reads digits in that base; base 0 takes the base from a 0x / 0o / 0b prefix like a Python literal.
  3. float(text) accepts decimals like '.5', '5.', '1e3' and the names inf, infinity and nan, then rounds to the nearest double.
  4. int() of a float truncates toward zero; str() gives the printed form (repr digits for floats).
  5. 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.

Educational simulation

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.

Key point

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?

  • Python skips the except clause and prints the calculated result

  • Python jumps to the except clause and skips the remaining try statements

  • Python converts hello to a number automatically

  • Python repeats the conversion without running any other code

Reveal answer
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.

User inputhellofloat conversionValueErrorCelsius calculationPlease enter a numberexcept clausefriendly messageattempt conversionif conversion succeedsif ValueError occurshandle error
What happens next when Python encounters invalid input during string-to-floating-point conversion?

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

Definition

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.

Code walkthrough
inp = input("Enter a Fahrenheit temperature: ")

try:
    fahrenheit = float(inp)
    celsius = (fahrenheit - 32) * 5 / 9
    print(celsius)
except ValueError:
    print("Please enter a number")
  1. 1
    input collects the user's response as text.
  2. 2
    float attempts to convert that text into a floating-point number.
  3. 3
    If the conversion succeeds, the calculation and print statement can run.
  4. 4
    If float raises ValueError, Python skips the remaining try statements.
  5. 5
    The 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.
Output
Please enter a number

In 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

tryrisky operationsfloat(inp)may raise ValueErrorcalculationdepends on conversionexcept ValueErrorerror responsefriendly messageshown after failurecontainssuccess permitsfailure transfers controlruns
Which statements belong in the try clause, which belong in the except clause, and how are they connected?
Best practice

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

helloinvalid textValueErrorprogram stopshelloinvalid textPlease enter a numberdefined responseconversion failsexcept handles failure
How does program behavior change from an unhandled conversion error to a user-friendly error message?
Before
inp = input("Enter a Fahrenheit temperature: ")
fahrenheit = float(inp)
print(fahrenheit)

Invalid text produces an unhandled ValueError and the program stops.

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

    If float raises ValueError, the exception occurs before Python reaches the try clause, so the except clause cannot handle it.

    Do this instead

    Place the conversion inside the try clause.

  • Common mistake

    Continuing with the calculation after conversion fails

    What it looks like
    try:
        fahrenheit = float(inp)
        celsius = (fahrenheit - 32) * 5 / 9
    Why it fails

    When conversion fails, Python skips the remaining statements in the try clause. The calculation cannot use a successfully converted value.

    Do this instead

    Keep 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 like
    fahrenheit = float(inp)
    Why it fails

    An invalid response can stop the program without giving the user a clear next step.

    Do this instead

    Catch 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 fails

    A broad, unfocused try clause makes it harder to identify which operation caused the exception and what the except response is handling.

    Do this instead

    Keep the try clause focused on operations that might raise the expected exception and on calculations that depend on them.

Practice the Control Flow

EASY

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.
Worked example

Tracing an Invalid Response

A temperature converter receives the text hello instead of a numeric temperature. Determine which statements run.

  1. 1
    Collect input

    The program stores the user's response as text before entering the try clause.

  2. 2
    Attempt conversion

    float tries to convert hello into a floating-point number and raises ValueError.

  3. 3
    Skip dependent statements

    Python immediately leaves the try clause, so the calculation and result output do not run.

  4. 4
    Handle the exception

    Python runs the except clause and displays the user-friendly message selected by the programmer.

Result

The program handles the invalid response with a message instead of continuing to the calculation or stopping with an unhandled crash.

Key Takeaways

  1. 1
    Conversion of user input can raise an exception when the text is not suitable for the expected numeric conversion.
  2. 2
    The try clause contains code that might fail, while the except clause contains the response to an error.
  3. 3
    When an exception occurs, Python skips the remaining statements in the try clause and transfers control to except.
  4. 4
    Keeping conversion and dependent calculations inside try prevents the program from continuing without a valid converted value.
  5. 5
    Friendly 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.

Related concepts

More concepts starting with T