Type Casting in Python | Python Course | Dataplexa

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)
Your age is: 25
  • 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
7.5 <class 'float'> 9 <class '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(), or set().

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)
7 7 -3 42 10 1 0 Error: invalid literal for int() with base 10: '12.5'
  • int() always truncates toward zero — int(7.9) is 7, not 8. Use round() if you want rounding.
  • To convert a decimal string like "12.5" to an integer: chain the casts — int(float("12.5")) → gives 12.
  • Booleans are a subtype of integer in Python — True is literally 1 and False is literally 0.

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)
10.0 -5.0 3.14 100.0 -7.5 1.0 0.0 Error: could not convert string to float: 'hello'
  • float() is more flexible than int() 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)
100 3.99 True None [1, 2, 3] Student: Anjali | Score: 92 | Grade: A Student: Anjali | Score: 92 | Grade: A
  • 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
False False False False False False False False --- True True True True True
  • Truthiness lets you write cleaner conditions. Instead of if len(username) > 0:, you can write if username: — both check the same thing.
  • -99 is True — only the number 0 is falsy, not negative numbers.
  • A list [0] is True — 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))
<class 'str'> True False Converted to: 42 <class 'int'>
  • str.isdigit() returns True if the string contains only digit characters — use it to validate before casting.
  • isinstance() is preferred over type() == 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)
As set: {'coding', 'python', 'tutorial', 'beginner'} Back to list: ['coding', 'python', 'tutorial', 'beginner'] Sorted: ['beginner', 'coding', 'python', 'tutorial'] As tuple: ('python', 'coding', 'python', 'tutorial', 'coding', 'beginner') Editable list: ['python', 'coding', 'python', 'tutorial', 'coding', 'beginner', 'advanced'] Characters: ['P', 'y', 't', 'h', 'o', 'n']
  • 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 call list() 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
Error 1: invalid literal for int() with base 10: 'hello' Error 2: invalid literal for int() with base 10: '9.5' Error 3: int() argument must be a string, a bytes-like object or a real number, not 'NoneType' Fixed: 9 42 0 -1
  • 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))
Item Price : Rs.299 Quantity : 4 Subtotal : Rs.1196 Discount : Rs.119.6 Final Total: Rs.1076.4

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}")
Product : Laptop Price : 89999.99 Qty : 12 In Stock: True Rating : 4.5 Total inventory value: Rs.10,79,999.88
  • 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)
As integers: [10, 25, 8, 42, 17] Sum: 102 Max: 42 As floats: [10.0, 25.0, 8.0, 42.0, 17.0] As strings: ['10', '25', '8', '42', '17']
  • map(int, list) applies int() to every item — the list() 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

MistakeWhat HappensFix
int("hello")ValueError — not a numberValidate with isdigit() first
int("9.5")ValueError — has decimal pointUse int(float("9.5"))
int(None)TypeError — None cannot be castCheck with if value is not None
float("$10.99")ValueError — symbol not allowedStrip symbol: float(s.replace("$",""))
"age: " + 25TypeError — str + int not allowedUse str(25) or f-string
int(7.9) expecting 8Returns 7 — truncates, not roundsUse round(7.9) for rounding

Complete Casting Functions Summary

FunctionConverts ToExample InputResult
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()Listlist((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 stringint(float("9.5"))9
type()Check current typetype("hello")<class 'str'>
isinstance()Check if type matchesisinstance(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)





NEXT UP
Basic Programs in Python
Put everything together — variables, loops, conditions, lists, and type casting — to build complete small programs that solve real problems from scratch.