Tutorials Python Python Type Casting
Ch 10 / 58
Python Beginner 8 min read Chapter 10 of 58

Python Type Casting

Python is strongly typed — it won't silently mix incompatible types for you. Type casting (also called type conversion) is how you intentionally change a value's data type. This chapter covers both implicit (automatic) and explicit (manual) conversion, every built-in casting function, common pitfalls that raise exceptions, and real-world use cases every Python developer encounters daily.

What you'll learn in this chapter
What type casting is and why it matters
Implicit (automatic) type conversion rules
Explicit casting with int(), float(), str()
bool(), list(), tuple(), set(), dict() casting
Common errors: ValueError, TypeError pitfalls
Real-world use cases and safe casting patterns
Advertisement

What is Type Casting?

Type casting (or type conversion) is the process of converting a value from one data type to another. Python is a strongly typed language — it never silently mixes incompatible types (unlike JavaScript). You must explicitly tell Python when you need a different type.

There are two kinds: implicit conversion (Python does it automatically in safe situations) and explicit conversion (you call a function like int(), float(), or str() to force a conversion).

Why type casting matters The most common real-world use: input() always returns a string. If a user types 25, Python still sees "25". You must cast it with int(input()) before doing arithmetic — otherwise you get TypeError.
Implicit
Python converts automatically
Explicit
You call int(), str(), etc.
ValueError
Invalid cast raises error
Strongly Typed
No silent surprises

Implicit Type Conversion

Implicit conversion happens automatically when Python promotes a value to a compatible "wider" type during an operation — without you writing any casting function. This only occurs in numeric expressions where no data is lost. The hierarchy is: int → float → complex.

Python — implicit_conversion.py
# int + float → Python auto-promotes int to float
a = 10        # int
b = 3.5       # float
result = a + b
print(result)           # 13.5
print(type(result))    # <class 'float'>

# int + complex → promoted to complex
c = 5 + 2j
d = 3
r2 = c + d
print(r2)               # (8+2j)
print(type(r2))        # <class 'complex'>

# float + complex → complex
r3 = 1.5 + 2j
print(type(r3))        # <class 'complex'>

# True/False are ints (1 and 0) — implicit in arithmetic
print(True + 9)        # 10  (True == 1)
print(False + 7)       # 7   (False == 0)
print(True + 2.5)      # 3.5 (True=1, promoted to float)

# Python DOES NOT auto-convert str → int or str → float
# "5" + 3  →  TypeError! (must use int("5") explicitly)
int + float → float
Python promotes int to float automatically because converting int → float never loses information.
int + complex → complex
Integers become complex numbers with zero imaginary part (e.g. 3 → 3+0j) automatically.
bool is int
True and False are instances of int — True == 1 and False == 0 in all arithmetic contexts.
str + int → TypeError
Python never implicitly converts strings to numbers. "5" + 3 raises TypeError — you must cast explicitly.
Expression Result Type Result Why
3 + 2.0 float 5.0 int promoted to float
3 + 2j complex (3+2j) int promoted to complex
True + 4 int 5 True == 1
False * 99 int 0 False == 0
"5" + 3 TypeError — No implicit str→int

Explicit Type Conversion

Explicit conversion means you deliberately call a built-in function to convert a value. Python provides dedicated functions for every built-in type. Each function creates and returns a new object — the original value is unchanged.

Python — explicit_overview.py
# Every Python built-in type has a constructor that casts

int("42")          # str  → int     → 42
int(3.9)           # float→ int     → 3  (truncates)
float("3.14")      # str  → float   → 3.14
float(7)           # int  → float   → 7.0
str(100)           # int  → str     → "100"
str(3.14)          # float→ str     → "3.14"
bool(0)            # int  → bool    → False
bool("hello")     # str  → bool    → True
list((1,2,3))      # tuple→ list    → [1, 2, 3]
tuple([1,2,3])   # list → tuple   → (1, 2, 3)
set([1,2,2,3])  # list → set     → {1, 2, 3} (no dups)
complex(3, 4)     # ints → complex → (3+4j)
The golden rule Not every cast is valid. int("hello") raises a ValueError because "hello" is not a numeric string. Always validate user input before casting, or wrap casts in a try/except block.
Advertisement
K2infocom Python Masterclass & Backend Development
Master Python, Django & Backend APIs with AI
Go from absolute beginner to building production-ready REST APIs, web applications, and ML pipelines. Real projects, live mentoring in Vadodara, and placement support included.
2,400+
Students Enrolled
4.9 ⭐
Google Rating
6 Months
Full Program
100%
Placement Support
Python 3 Django & DRF FastAPI PostgreSQL Machine Learning Docker & AWS Real Projects AI Tools

Casting to Integer — int()

int() converts a value to a whole number. It accepts floats (truncating, not rounding), numeric strings in any base, and booleans. It raises ValueError for non-numeric strings and TypeError for unsupported types.

Python — int_casting.py
# float → int  (truncates toward zero, never rounds)
print(int(3.9))         # 3
print(int(3.1))         # 3
print(int(-3.9))        # -3  (toward zero, not -4)

# str → int  (string must be a valid integer literal)
print(int("42"))        # 42
print(int("-17"))       # -17
print(int("  50  "))    # 50  (leading/trailing whitespace OK)

# str → int with explicit base (2=binary, 8=octal, 16=hex)
print(int("1010", 2))   # 10   (binary string)
print(int("FF",   16))  # 255  (hex string)
print(int("0xFF", 16))  # 255  (hex with prefix)
print(int("17",   8))   # 15   (octal string)

# bool → int
print(int(True))        # 1
print(int(False))       # 0

# ❌ These RAISE errors:
# int("3.14")   → ValueError  (float string not valid for int())
# int("hello")  → ValueError
# int([1,2,3])  → TypeError   (lists can't be cast to int)
# int(3+4j)     → TypeError   (complex can't be cast to int)

# ✅ Safe pattern with try/except
user_input = "abc"
try:
    n = int(user_input)
    print(f"Valid integer: {n}")
except ValueError:
    print(f"'{user_input}' is not a valid integer")
Common mistake int("3.14") raises ValueError — even though 3.14 looks numeric. You must first convert to float: int(float("3.14")) → 3.

Casting to Float — float()

float() converts a value to a decimal number. It accepts integers, numeric strings (including scientific notation), booleans, and the special string literals "inf", "-inf", and "nan".

Python — float_casting.py
# int → float
print(float(7))          # 7.0
print(float(-3))         # -3.0

# str → float  (decimal strings and scientific notation)
print(float("3.14"))     # 3.14
print(float("-0.001"))   # -0.001
print(float("1.5e3"))    # 1500.0  (scientific notation)
print(float("42"))       # 42.0    (integer string works too)

# Special float values from strings
print(float("inf"))      # inf
print(float("-inf"))     # -inf
print(float("nan"))      # nan

# bool → float
print(float(True))       # 1.0
print(float(False))      # 0.0

# Practical example: reading a price from user input
price_str = "99.99"      # simulating input()
price = float(price_str)
tax = price * 0.18
print(f"Price: ₹{price:.2f}, Tax: ₹{tax:.2f}")
# Price: ₹99.99, Tax: ₹17.998

# ❌ These RAISE errors:
# float("hello")   → ValueError
# float([1, 2])    → TypeError

Casting to String — str()

str() converts any Python object to its string representation. It never raises an error — every Python object has a string form. This is the cast used most often when building output, log messages, and file contents.

Python — str_casting.py
# Any type → string
print(str(42))           # "42"
print(str(3.14))         # "3.14"
print(str(True))         # "True"
print(str(None))         # "None"
print(str([1,2,3]))     # "[1, 2, 3]"
print(str({"a":1}))      # "{'a': 1}"
print(str(3+4j))        # "(3+4j)"

# ✅ str() never raises an error — all objects are printable

# Practical: building a message string from mixed types
name  = "Alice"
age   = 25
score = 98.5

# ❌ Wrong: "Name: " + name + " Age: " + age  → TypeError
# ✅ Fix 1: cast int to str explicitly
print("Name: " + name + " Age: " + str(age))
# Name: Alice Age: 25

# ✅ Fix 2 (preferred): use f-strings — no cast needed
print(f"Name: {name}, Age: {age}, Score: {score}")
# Name: Alice, Age: 25, Score: 98.5

# str() vs repr() — repr gives developer-friendly output
s = "hello\nworld"
print(str(s))            # hello        (interprets \n)
                          # world
print(repr(s))           # 'hello\nworld' (shows raw escape)
Prefer f-strings over str() concatenation Instead of "Value: " + str(x), write f"Value: {x}". F-strings automatically call the string representation of every embedded expression — cleaner, faster, and more readable.

bool(), list(), tuple(), set() & dict()

Beyond numeric and string casts, Python provides casting functions for booleans and all collection types. Understanding truthiness (what evaluates to False) is particularly important for conditionals and filtering.

bool() — Truthiness Rules

Python — bool_casting.py
# Falsy values — these all produce False
print(bool(0))           # False  — zero int
print(bool(0.0))         # False  — zero float
print(bool(""))          # False  — empty string
print(bool([]))          # False  — empty list
print(bool(()))          # False  — empty tuple
print(bool({}))          # False  — empty dict
print(bool(set()))       # False  — empty set
print(bool(None))        # False  — None

# Truthy values — everything else is True
print(bool(1))           # True
print(bool(-99))         # True  (any non-zero number)
print(bool("0"))         # True  (non-empty string, even "0"!)
print(bool("False"))     # True  (non-empty string!)
print(bool([0]))         # True  (list with one element)
print(bool(0.001))       # True

# Practical use: check if a list has items
items = [1, 2, 3]
if items:                # same as: if bool(items):
    print("List has items")

Collection Type Casting

Python — collection_casting.py
# list() — cast any iterable to a list
print(list((1, 2, 3)))        # [1, 2, 3]  — tuple → list
print(list({1, 2, 3}))        # [1, 2, 3]  — set → list (unordered)
print(list("hello"))           # ['h','e','l','l','o'] — str→ list
print(list(range(5)))          # [0, 1, 2, 3, 4]  — range → list

# tuple() — cast any iterable to a tuple (immutable)
print(tuple([1, 2, 3]))       # (1, 2, 3)
print(tuple("abc"))           # ('a', 'b', 'c')
print(tuple(range(4)))         # (0, 1, 2, 3)

# set() — removes duplicates automatically!
print(set([1, 2, 2, 3, 3]))  # {1, 2, 3}
print(set("hello"))           # {'h', 'e', 'l', 'o'} (unique chars)

# dict() — create a dict from key-value pairs
print(dict(name="Alice", age=25))
# {'name': 'Alice', 'age': 25}

print(dict([("a",1), ("b",2)]))
# {'a': 1, 'b': 2}

# Common pattern: remove duplicates while preserving order
nums = [3, 1, 4, 1, 5, 9, 2, 6, 5]
unique = list(dict.fromkeys(nums))
print(unique)               # [3, 1, 4, 5, 9, 2, 6]
Function Converts Notes
int(x) float, str, bool → int Truncates floats; ValueError on non-numeric strings
float(x) int, str, bool → float Accepts "inf", "nan"; ValueError on non-numeric strings
str(x) Any object → str Never raises an error; all objects have a string form
bool(x) Any object → bool Falsy: 0, "", [], {}, (), None; everything else is True
list(x) Any iterable → list Strings become lists of characters
tuple(x) Any iterable → tuple Immutable version of list
set(x) Any iterable → set Removes duplicates; unordered
complex(r, i) int/float → complex Cannot convert str directly

Practice Python Online — Free Compilers

Don't want to install anything yet? Practice all type casting examples from this chapter directly in your browser with these free Python environments.

▶
Online Python 3 Compiler
Write, run and debug Python code in your browser. No installation required. Supports all type casting and conversion examples.
Open Compiler
Replit
Full IDE online
Google Colab
Free GPU notebooks
JupyterLite
Notebooks in browser
Programiz
Beginner-friendly
Chapter Summary
  • Type casting converts a value from one data type to another. Python has two kinds: implicit (automatic) and explicit (manual).
  • Implicit conversion only happens in safe numeric promotions: int → float → complex. Python never implicitly converts strings to numbers.
  • int(x) — truncates floats (not rounds); accepts numeric strings and an optional base (2, 8, 16). Raises ValueError for non-numeric strings.
  • float(x) — converts int, numeric strings, and special values like "inf" and "nan". Use float("3.14") before int() for decimal strings.
  • str(x) — converts any object to its string form. Never raises an error. Prefer f-strings over str() concatenation.
  • Falsy values: 0, 0.0, "", [], (), {}, set(), None. Everything else is truthy — including "0" and "False".
  • set() automatically removes duplicates. list(dict.fromkeys(x)) removes duplicates while preserving insertion order.
  • Always wrap user-input casts in try/except ValueError — never trust raw input to be the right type.
⚡
Free Resource
Download our Python Type Casting Cheat Sheet
All casting functions, implicit rules, falsy values & common errors — one printable page.
Get Sheet
Advertisement
Quick Check — Test Your Understanding
Question & Answer
✓ Answer

Implicit conversion (also called coercion) happens automatically when Python detects a safe promotion between compatible types during an operation. It only occurs in numeric contexts where no data is lost — such as int + float producing a float, or int + complex producing a complex. You write no extra code — Python handles it silently.

Explicit conversion requires you to call a built-in function — int(), float(), str(), bool(), etc. — to deliberately change a value's type. This is needed whenever the conversion could lose data (float → int truncates) or could fail (a non-numeric string cannot become an int). Explicit is safer because the developer consciously handles the conversion.

✓ Answer

int() accepts only strings that represent whole integers in a valid base. The string "3.14" contains a decimal point, making it a float literal — not an integer literal. Python's int() parser refuses it and raises ValueError: invalid literal for int() with base 10: '3.14'. The fix is a two-step cast:

# Step 1: str → float, Step 2: float → int
int(float("3.14"))   # → 3  (truncated, not rounded)
round(float("3.7"))   # → 4  (if rounding is needed)
✓ Answer

The complete set of falsy values in Python: False, None, 0, 0.0, 0j, "" (empty string), [] (empty list), () (empty tuple), {} (empty dict), set() (empty set), and b"" (empty bytes). Everything else is truthy.

bool("False") is True because the string "False" is a non-empty string. Python's bool() for strings only checks length — any string with at least one character is truthy, regardless of what that character or word is. "False", "0", and "no" are all truthy strings.

✓ Answer

input() always returns a string. If the user types a non-numeric value and you call int() on it directly, Python raises ValueError and crashes. The safe pattern is to use try/except:

while True:
    raw = input("Enter a number: ")
    try:
        n = int(raw)
        break
    except ValueError:
        print("Not a valid integer, try again.")
print(f"You entered: {n}")
✓ Answer
  • set(lst) — removes duplicates but does not preserve insertion order. The result is an unordered set. To get a list back: list(set(lst)). Use when order does not matter.
  • list(dict.fromkeys(lst)) — removes duplicates while preserving the original insertion order. In Python 3.7+ dictionaries maintain insertion order, so this is the correct idiom for order-sensitive deduplication. Use when order matters.
  • Example: [3,1,2,1,3] → set() gives {1,2,3} (order not guaranteed), while dict.fromkeys() gives [3,1,2] (original order preserved).
MCQ 1 of 3
What does int(3.9) return in Python?
MCQ 2 of 3
Which of the following evaluates to False in Python?
MCQ 3 of 3
What does int("1010", 2) return?

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel