Python Type Casting

Convert values between types with int(), float(), str() and bool(), and know which conversions fail, truncate or surprise.

Lesson 8 of 107Beginner11 min read

Type casting in Python means creating a value of one type from a value of another, using the type's name as a function: int("27") gives the integer 27, str(27) gives the text "27", float("4.5") gives 4.5, and bool(0) gives False.

Python
tickets = int("27")         # text from a file becomes a number
print(tickets * 4.5)        # 121.5
label = "Tickets: " + str(tickets)

Python converts automatically in only a few situations, such as mixing int and float in arithmetic. Everywhere else you convert explicitly, which is safer because it makes your intention visible. This lesson covers the four main conversion functions, the text formats they accept, how int() truncates decimals, and why bool("False") is True. The examples follow a museum importing ticket quantities from text files.

Conversion functions

FunctionAcceptsExampleResult
int(x)integer text, floats, boolsint(" 42 ")42
float(x)number text, intsfloat("1e3")1000.0
str(x)anythingstr(3.50)"3.5"
bool(x)anythingbool("")False

These functions don't change the original value; they return a new one. int() and float() ignore surrounding whitespace and accept a leading + or -, plus underscores between digits (int("1_000")). float() also understands "inf" and "nan".

When the text isn't in a valid format, the conversion raises ValueError, for example int("27 tickets"). Converting something of the wrong kind entirely, such as int([1, 2]) or int(None), raises TypeError. Plan for both whenever data comes from outside your program.

Integer parsing

int() reads base-10 digits by default. A second argument sets the base, which is useful for binary flags, hexadecimal colour codes and octal file permissions:

Python
print(int("1011", 2))     # 11
print(int("ff", 16))      # 255
print(int("0x1f", 0))     # 31: base 0 reads the prefix

The reverse conversions are bin(11) ('0b1011'), hex(255) ('0xff') and format codes such as f"{255:08b}".

int() only parses integer text. int("2.7") raises ValueError even though 2.7 is a perfectly good number, because the string contains a decimal point. Convert in two steps when the text may contain decimals: int(float("2.7")), remembering the truncation rule below.

Truncation

Applied to a float, int() truncates: it throws away the fractional part, moving towards zero. That is not the same as rounding or flooring:

Valueint()round()math.floor()
3.8343
-3.8-3-4-4
2.5222

For positive numbers truncation and floor agree; for negative numbers they don't. Choose deliberately: round() for the nearest whole number, math.floor() to always go down, math.ceil() to always go up (for example, "how many coaches for 130 visitors?"), and int() when you specifically want to drop the decimals. int(float("inf")) raises OverflowError, and int(float("nan")) raises ValueError.

Truth conversion

bool() follows Python's truth rules; it does not read words. False, None, zero of any numeric type and empty containers ("", [], {}, (), set()) are false. Everything else is true, including the strings "0", "False" and " ":

Python
print(bool(""), bool("0"), bool("False"))   # False True True

So reading "false" from a settings file and calling bool() on it gives True. Parse words explicitly instead:

Python
raw = "False"
enabled = raw.strip().lower() in ("true", "yes", "1", "on")
print(enabled)   # False

int() and float() work on booleans because bool is a subclass of int: int(True) is 1, which is why sum([True, False, True]) counts the true values.

Independent practice and a worked check

Task: parse ticket quantities and report invalid records without silently substituting zero. Given ["12", " 7 ", "3.5", "", "x9"], convert each valid whole number, collect the invalid ones with their reason, and print the total.

Python
raw_values = ["12", " 7 ", "3.5", "", "x9"]
valid, invalid = [], []
for raw in raw_values:
    try:
        valid.append(int(raw))
    except ValueError:
        invalid.append(raw)

print("Total:", sum(valid))       # Total: 19
print("Invalid:", invalid)        # Invalid: ['3.5', '', 'x9']

" 7 " converts because int() ignores surrounding spaces; "3.5" fails because it isn't integer text; the empty string fails too. For the worked check, int(-3.8) produces -3: truncation moves towards zero.

Reference and next practice

The built-in function reference documents int(), float() and bool(). Continue with booleans and expressions to see truth rules in conditions, and the numbers lesson for rounding. Practise with the Python exercises and Python quiz.

Type Casting Summary

  • Conversion functions: int, float, str and bool request values of a particular type.
  • Integer parsing: int accepts integer text and supports an explicit numeric base.
  • Truncation: int applied to a finite float discards the fractional part toward zero.
  • Truth conversion: bool follows truth value rules rather than parsing words.

Type Casting Examples

Each example shows the code, the output it produces and what each part does.

Example 1

Type Casting in a small program

Python
tickets = int("27")
print(tickets * 4.5)
print(int(-3.8))
Output
121.5
-3
Line-by-line explanation
  1. Line 1The text "27" becomes the integer 27.
  2. Line 2Multiplying an int by a float gives a float, so Python converts automatically here.
  3. Line 3int() truncates towards zero, so -3.8 becomes -3, not -4.
Example 2

Importing ticket records safely

Python
rows = ["Adult,27", "Child,12", "Family,two", "Senior,-1", "Student,8"]

totals = {}
problems = []
for row in rows:
    kind, raw_qty = row.split(",")
    try:
        qty = int(raw_qty)
    except ValueError:
        problems.append(f"{kind}: {raw_qty!r} is not a whole number")
        continue
    if qty < 0:
        problems.append(f"{kind}: negative quantity {qty}")
        continue
    totals[kind] = qty

print(totals)
print(sum(totals.values()), "tickets")
for problem in problems:
    print("Check:", problem)
Output
{'Adult': 27, 'Child': 12, 'Student': 8}
47 tickets
Check: Family: 'two' is not a whole number
Check: Senior: negative quantity -1
Line-by-line explanation
  1. Lines 7 to 11A failed conversion is recorded and skipped rather than replaced with 0.
  2. Lines 12 to 14A successful conversion still has to pass the business rule.
  3. Lines 18 to 19Every rejected record is reported, so someone can correct the source file.

Common Type Casting Mistakes

Using bool() to read "true" and "false" text

Don't
setting = "false"
if bool(setting):
    print("Gift shop open")    # runs: any non-empty string is True
Do
setting = "false"
if setting.strip().lower() == "true":
    print("Gift shop open")

bool() only checks whether the string is empty. Compare the text itself when it contains a word.

Passing decimal text straight to int()

Don't
qty = int("2.0")            # ValueError
Do
qty = int(float("2.0"))     # 2

int() parses integer text only. Convert to float first, and decide whether truncating is acceptable.

Type Casting in Real Projects

Conversions at system boundaries

Every value that enters a program from outside starts as text or bytes: CSV cells, form fields, command-line arguments, environment variables and JSON strings. Robust programs convert at that boundary, once, and work with proper types everywhere else. Libraries help: csv gives you strings, json already returns numbers and booleans, and pandas can parse whole columns with pd.to_numeric(column, errors="coerce").

For the museum, converting at import time means the totals, prices and reports never see a stray string, and a single "problems" list shows staff exactly which records to fix. Silently replacing bad values with zero would produce believable but wrong attendance figures.

Type Casting FAQ

What is the difference between type casting and type conversion in Python?

In Python the terms are used interchangeably. Both mean creating a value of a new type, usually by calling int(), float(), str() or bool(). Python performs a few implicit conversions itself, such as turning an int into a float when you add 1 + 2.5.

How do I convert a float to an int with rounding?

Use round(x) for the nearest integer, which already returns an int when called with one argument. math.ceil(x) and math.floor(x) also return integers. int(x) truncates instead of rounding, so int(2.9) is 2.

How do I check if a string can be converted to a number?

The most reliable way is to try the conversion inside try/except ValueError. String methods such as isdigit() reject valid input like "-5" and "3.5", so they are only suitable when you want positive whole numbers.

How do I convert a list of strings to integers?

Use a list comprehension, [int(x) for x in items], or list(map(int, items)). Either raises ValueError on the first invalid string, so validate first or convert inside a loop with try if the data may be messy.

Why does str(3.50) give "3.5"?

A float doesn't remember how many decimal places you typed, so str() produces the shortest text that represents the value. Use formatting when you need a fixed number of decimals: f"{3.5:.2f}" gives "3.50".

Type Casting Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Multiple choiceeasy

What does int(-3.8) produce?

Multiple choicemedium

Which review concern is valid for type casting?

Type Casting Quiz

2 questions to check what you learned.

  1. What does int(-3.8) produce?

    • -4
    • -3
    • Python ignores the distinction
  2. Which statement correctly describes truncation?

    • int applied to a finite float discards the fractional part toward zero.
    • Only the example output matters, not the rule
    • Every operation has the same behavior