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.
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
| Function | Accepts | Example | Result |
|---|---|---|---|
int(x) | integer text, floats, bools | int(" 42 ") | 42 |
float(x) | number text, ints | float("1e3") | 1000.0 |
str(x) | anything | str(3.50) | "3.5" |
bool(x) | anything | bool("") | 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:
print(int("1011", 2)) # 11
print(int("ff", 16)) # 255
print(int("0x1f", 0)) # 31: base 0 reads the prefixThe 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:
| Value | int() | round() | math.floor() |
|---|---|---|---|
3.8 | 3 | 4 | 3 |
-3.8 | -3 | -4 | -4 |
2.5 | 2 | 2 | 2 |
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 " ":
print(bool(""), bool("0"), bool("False")) # False True TrueSo reading "false" from a settings file and calling bool() on it gives True. Parse words explicitly instead:
raw = "False"
enabled = raw.strip().lower() in ("true", "yes", "1", "on")
print(enabled) # Falseint() 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.
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.
Type Casting in a small program
tickets = int("27")
print(tickets * 4.5)
print(int(-3.8))121.5
-3Line-by-line explanation
- Line 1The text
"27"becomes the integer 27. - Line 2Multiplying an
intby afloatgives a float, so Python converts automatically here. - Line 3
int()truncates towards zero, so -3.8 becomes -3, not -4.
Importing ticket records safely
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){'Adult': 27, 'Child': 12, 'Student': 8}
47 tickets
Check: Family: 'two' is not a whole number
Check: Senior: negative quantity -1Line-by-line explanation
- Lines 7 to 11A failed conversion is recorded and skipped rather than replaced with 0.
- Lines 12 to 14A successful conversion still has to pass the business rule.
- 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
setting = "false"
if bool(setting):
print("Gift shop open") # runs: any non-empty string is Truesetting = "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()
qty = int("2.0") # ValueErrorqty = int(float("2.0")) # 2int() 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.
What does int(-3.8) produce?
Which review concern is valid for type casting?
Type Casting Quiz
2 questions to check what you learned.
What does int(-3.8) produce?
- -4
- -3
- Python ignores the distinction
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