
Python Course
Type Casting in Python
Every value in Python has a data type — 25 is an integer, "25" is a string, and 25.0 is a float. These types behave differently: you can multiply an integer by 3, but multiplying a string by 3 repeats it three times. When you need to use data in a different type than it currently is, you convert it — and that process is called type casting.
Type casting is something every real Python program does constantly. When a user types their age into a form, Python receives it as a string. Before doing any math, you must cast it to an integer. When you load data from a CSV file, every value arrives as a string. When building a display message, you must cast numbers back to strings to join them with text. Understanding type casting well removes one of the most common sources of bugs in beginner Python programs.
Why Type Casting Matters
Python is a strongly typed language — it does not automatically convert between unrelated types. Try to add a number and a string directly, and Python raises a TypeError immediately rather than guessing what you meant.
# Python refuses to guess — this raises TypeError
age = 25
message = "Your age is: " + age # crash!
# You must explicitly convert
message = "Your age is: " + str(age) # correct
print(message)
- Python protects you from accidental data mixing — a feature, not a limitation.
- You are in full control of every conversion. Nothing happens behind your back.
Implicit vs Explicit Type Casting
Python has two modes of type casting. Implicit casting is automatic — Python does it silently when it is safe to do so. Explicit casting is manual — you call a function to convert the value yourself.
# IMPLICIT — Python automatically promotes int to float
a = 5 # integer
b = 2.5 # float
result = a + b
print(result) # 7.5 — Python converted 5 to 5.0 quietly
print(type(result)) # float
# EXPLICIT — you convert manually
x = 9.99
y = int(x) # you are explicitly cutting the decimal
print(y) # 9 — not rounded, just truncated
print(type(y)) # int
- Implicit casting only happens from int to float — going from a smaller, more restrictive type to a larger one that can hold the value without any loss.
- Python never implicitly converts float to int (that would lose the decimal), or between numbers and strings (completely different kinds of data).
- Explicit casting always goes through a built-in function:
int(),float(),str(),bool(),list(),tuple(), orset().
Converting to Integer — int()
The int() function converts a value into a whole number. It accepts floats (removes the decimal — does NOT round), strings that contain only whole number digits, and booleans.
# float to int — decimal is truncated, not rounded
print(int(7.1)) # 7
print(int(7.9)) # 7 — still 7, NOT 8
print(int(-3.8)) # -3 — truncates toward zero
# string to int — works only for whole number strings
print(int("42")) # 42
print(int(" 10 ")) # 10 — strips whitespace automatically
# bool to int — True = 1, False = 0
print(int(True)) # 1
print(int(False)) # 0
# This fails — string with decimal cannot go directly to int
try:
print(int("12.5"))
except ValueError as e:
print("Error:", e)
int()always truncates toward zero —int(7.9)is7, not8. Useround()if you want rounding.- To convert a decimal string like
"12.5"to an integer: chain the casts —int(float("12.5"))→ gives12. - Booleans are a subtype of integer in Python —
Trueis literally1andFalseis literally0.
Converting to Float — float()
The float() function converts a value into a decimal number. Unlike int(), it can handle both whole number strings and decimal strings.
# int to float — adds decimal point
print(float(10)) # 10.0
print(float(-5)) # -5.0
# string to float — works with both whole and decimal strings
print(float("3.14")) # 3.14
print(float("100")) # 100.0
print(float("-7.5")) # -7.5
# bool to float
print(float(True)) # 1.0
print(float(False)) # 0.0
# fails — non-numeric string
try:
print(float("hello"))
except ValueError as e:
print("Error:", e)
float()is more flexible thanint()for string conversion — it handles decimal strings directly.- Use
float()when you need precision — prices, measurements, scientific values, percentages.
Converting to String — str()
The str() function converts any value into a string. This is used constantly when building messages, writing to files, or combining numbers with text. str() never fails — every Python value has a string representation.
print(str(100)) # "100"
print(str(3.99)) # "3.99"
print(str(True)) # "True"
print(str(None)) # "None"
print(str([1,2,3])) # "[1, 2, 3]"
# Practical use: combining numbers with text using +
name = "Anjali"
score = 92
grade = "A"
# Without str(), the + would crash (TypeError)
report = "Student: " + name + " | Score: " + str(score) + " | Grade: " + grade
print(report)
# Modern alternative: f-strings (no conversion needed)
report2 = f"Student: {name} | Score: {score} | Grade: {grade}"
print(report2)
- F-strings (covered in Lesson 9) automatically handle the conversion — they are cleaner for output building.
str()with+concatenation is useful when you need the string result stored in a variable for later use.
Converting to Boolean — bool()
The bool() function converts any value to True or False. Python has a consistent rule: empty or zero values are False, everything else is True. This property is called truthiness and is used everywhere in Python conditional logic.
# These all become FALSE
print(bool(0)) # zero integer
print(bool(0.0)) # zero float
print(bool("")) # empty string
print(bool([])) # empty list
print(bool({})) # empty dict
print(bool(())) # empty tuple
print(bool(set())) # empty set
print(bool(None)) # None
print("---")
# These all become TRUE
print(bool(1)) # any non-zero number
print(bool(-99)) # negative numbers too
print(bool("hello")) # any non-empty string
print(bool([0])) # a list with one item (even if item is 0)
print(bool({"a":1})) # non-empty dict
- Truthiness lets you write cleaner conditions. Instead of
if len(username) > 0:, you can writeif username:— both check the same thing. -99isTrue— only the number0is falsy, not negative numbers.- A list
[0]isTrue— it is not empty even though it contains a zero.
Checking Type Before and After Casting
Python gives you two tools to inspect types. type() tells you what type a value currently is. isinstance() checks if a value belongs to a specific type and returns True or False — better for writing conditions.
value = "42"
# type() — shows the exact type
print(type(value)) # <class 'str'>
# isinstance() — for conditional checks
print(isinstance(value, str)) # True
print(isinstance(value, int)) # False
# Professional pattern: check before casting
if isinstance(value, str) and value.strip().isdigit():
value = int(value)
print("Converted to:", value, type(value))
str.isdigit()returns True if the string contains only digit characters — use it to validate before casting.isinstance()is preferred overtype() ==in professional code because it also works with subclasses.
Converting Between Collections
You can freely convert between lists, tuples, and sets. This is extremely practical — the most common pattern is converting a list to a set to remove duplicates, then back to a sorted list.
# A list of tags with duplicates
tags = ["python", "coding", "python", "tutorial", "coding", "beginner"]
# list → set (removes duplicates)
unique = set(tags)
print("As set:", unique)
# set → list (so you can sort and index)
clean = list(unique)
print("Back to list:", clean)
print("Sorted:", sorted(clean))
# list → tuple (makes it immutable)
fixed = tuple(tags)
print("As tuple:", fixed)
# tuple → list (makes it editable)
editable = list(fixed)
editable.append("advanced")
print("Editable list:", editable)
# string → list of characters
word = "Python"
chars = list(word)
print("Characters:", chars)
list("Python")splits a string into its individual characters — a common trick when processing text character by character.sorted()always returns a list, so you do not need to calllist()separately after sorting a set.
Safe Casting — Handling Errors Gracefully
Casting fails when the value cannot be logically converted. The professional approach is to wrap risky conversions in a try-except block or validate the value first. This prevents crashes when working with user input or external data.
# Common failures
try:
print(int("hello")) # ValueError — not a number
except ValueError as e:
print("Error 1:", e)
try:
print(int("9.5")) # ValueError — has a decimal
except ValueError as e:
print("Error 2:", e)
try:
print(int(None)) # TypeError — None cannot be cast
except TypeError as e:
print("Error 3:", e)
# Fix for decimal string: chain the casts
print("Fixed:", int(float("9.5"))) # 9
# Safe casting function pattern
def safe_int(value, default=0):
try:
return int(value)
except (ValueError, TypeError):
return default
print(safe_int("42")) # 42 — success
print(safe_int("hello")) # 0 — uses default
print(safe_int(None, -1)) # -1 — custom default
- The
safe_int()pattern is used in production code constantly — never crash, always return a safe fallback. - Always chain for decimal strings:
int(float("9.5"))→ first to float, then truncate to int.
Real World Example — Processing User Input
The most common place type casting appears in beginner programs: the input() function always returns a string, regardless of what the user typed. Every number must be cast before doing any math.
# Simulating what input() returns — always strings
price_str = "299"
quantity_str = "4"
discount_str = "10"
# Cast to numbers for calculation
price = int(price_str)
quantity = int(quantity_str)
discount = int(discount_str)
subtotal = price * quantity
discount_amt = subtotal * (discount / 100)
final_total = subtotal - discount_amt
# Cast back to string for display
print("Item Price : Rs." + str(price))
print("Quantity : " + str(quantity))
print("Subtotal : Rs." + str(subtotal))
print("Discount : Rs." + str(discount_amt))
print("Final Total: Rs." + str(final_total))
Real World Example — Cleaning Data from a File or API
When data arrives from a CSV file, database, or web API, every value is typically a string. Before processing, you must cast each field to the right type. This is one of the most common tasks in data engineering and data science.
# Simulating a row of data from a CSV file — all strings
raw_record = {
"product" : "Laptop",
"price" : "89999.99",
"quantity" : "12",
"in_stock" : "True",
"rating" : "4.5"
}
# Cast each field to the correct type
clean_record = {
"product" : raw_record["product"], # stays string
"price" : float(raw_record["price"]), # becomes float
"quantity" : int(raw_record["quantity"]), # becomes int
"in_stock" : raw_record["in_stock"] == "True", # becomes bool
"rating" : float(raw_record["rating"]) # becomes float
}
print("Product :", clean_record["product"])
print("Price :", clean_record["price"])
print("Qty :", clean_record["quantity"])
print("In Stock:", clean_record["in_stock"])
print("Rating :", clean_record["rating"])
# Now you can do real math with these values
total_value = clean_record["price"] * clean_record["quantity"]
print(f"Total inventory value: Rs.{total_value:,.2f}")
- The
"True" == "True"pattern converts a string boolean to a real Python boolean — a common trick when reading CSV data. f"Rs.{total_value:,.2f}"formats a float with commas and 2 decimal places inside an f-string.
Casting with map() — Converting an Entire List at Once
When you have a whole list of strings that need converting, using a loop is one approach but map() is more Pythonic — it applies a function to every item in one step.
# A list of number strings (common when reading CSV columns)
str_numbers = ["10", "25", "8", "42", "17"]
# Using map() to convert every item at once
int_numbers = list(map(int, str_numbers))
print("As integers:", int_numbers)
print("Sum:", sum(int_numbers))
print("Max:", max(int_numbers))
# Converting to floats the same way
float_numbers = list(map(float, str_numbers))
print("As floats:", float_numbers)
# Converting numbers back to strings
labels = list(map(str, int_numbers))
print("As strings:", labels)
map(int, list)appliesint()to every item — thelist()wrapper converts the result into a proper list.- This is the professional way to type-cast entire columns of data from CSV files or API responses.
Common Casting Mistakes — Quick Reference
| Mistake | What Happens | Fix |
|---|---|---|
int("hello") | ValueError — not a number | Validate with isdigit() first |
int("9.5") | ValueError — has decimal point | Use int(float("9.5")) |
int(None) | TypeError — None cannot be cast | Check with if value is not None |
float("$10.99") | ValueError — symbol not allowed | Strip symbol: float(s.replace("$","")) |
"age: " + 25 | TypeError — str + int not allowed | Use str(25) or f-string |
int(7.9) expecting 8 | Returns 7 — truncates, not rounds | Use round(7.9) for rounding |
Complete Casting Functions Summary
| Function | Converts To | Example Input | Result |
|---|---|---|---|
int() | Integer (whole number) | int("42"), int(3.9), int(True) | 42, 3, 1 |
float() | Float (decimal number) | float(5), float("3.14") | 5.0, 3.14 |
str() | String (text) | str(99), str(True), str(None) | "99", "True", "None" |
bool() | Boolean (True/False) | bool(0), bool("hi"), bool([]) | False, True, False |
list() | List | list((1,2,3)), list("abc") | [1,2,3], ['a','b','c'] |
tuple() | Tuple (immutable) | tuple([1,2,3]) | (1, 2, 3) |
set() | Set (unique items) | set([1,1,2,3]) | {1, 2, 3} |
int(float()) | Int from decimal string | int(float("9.5")) | 9 |
type() | Check current type | type("hello") | <class 'str'> |
isinstance() | Check if type matches | isinstance(42, int) | True |
Practice
Which function converts a string like "42" into a whole number?
What does int(7.9) return?
What does bool(0) return?
Which function must you use to join a number into a text sentence using +?
What error is raised when you run int("hello")?
What is the result of int(float("9.5"))?
Quick Quiz
What is the result of int(9.99)?
What does bool("hello") return?
When Python automatically converts an int to a float during addition, this is called __________ casting.
What is the correct way to convert the string "9.5" to an integer?
What does int(True) return?
What does bool([0]) return? (A list containing one zero)