DevHireLab
Tutorials
BootcampProblemsCode SimulatorAI InterviewSoonContact
DevHireLab
Tutorials
BootcampProblemsCode SimulatorAI InterviewSoonContact
Getting Started
01
What is Python and Why Learn It in 2026
02
Installing Python on Windows, Mac, and Linux
03
Setting up VS Code / PyCharm for Python
04
Understanding the Python Interpreter and REPL
05
Writing and Running Your First Python Program
06
Python Syntax and Indentation Rules
Variables and Data Types
01
Variables and Naming Conventions in Python
02
Numbers in Python (int, float, complex)
03
Strings and String Methods in Python
04
Booleans in Python
05
Type Conversion / Casting in Python
06
Understanding the None Type in Python
Operators
01
Arithmetic Operators in Python
02
Comparison Operators in Python
03
Logical Operators in Python
04
Assignment Operators in Python
05
Bitwise Operators in Python
06
Identity (is) and Membership (in) Operators
07
Walrus Operator (:=) in Python
Input, Output & Strings
01
input() and print() Functions in Python
02
f-strings and String Formatting in Python
03
String Slicing and Indexing in Python
04
Common String Methods (split, join, strip, replace)
05
Escape Characters in Python Strings
Control Flow
01
if, elif, else Statements in Python
02
Nested Conditionals in Python
03
for Loops in Python
04
while Loops in Python
05
break, continue, and pass Statements
06
Loop with else Clause in Python
07
match-case (Structural Pattern Matching)
Data Structures
01
Python Lists: Creation, Indexing, Slicing, Methods
02
Python Tuples and Immutability
03
Python Sets and Set Operations
04
Python Dictionaries: Keys, Values, and Methods
05
List Comprehensions in Python
06
Dictionary & Set Comprehensions in Python
07
Working with Nested Lists and Dictionaries
Functions
01
Defining and Calling Functions in Python
02
Function Arguments: Positional, Keyword, Default
03
*args and **kwargs in Python
04
Return Statements in Python Functions
05
Lambda Functions in Python
06
Recursion in Python
07
Variable Scope: Local, Global, Nonlocal
08
Docstrings and Function Annotations
Functional Programming Basics
01
map(), filter(), and reduce() in Python
02
Closures in Python Explained
03
Python Decorators: Basic to Advanced
04
Generators and yield in Python
Object-Oriented Programming (OOP)
01
Classes and Objects in Python
02
The init Constructor in Python
03
Instance vs Class Variables in Python
04
Inheritance in Python (Single, Multiple, Multilevel)
05
Polymorphism in Python
06
Encapsulation in Python
07
Abstraction in Python with the abc Module
08
Magic/Dunder Methods in Python
09
Static and Class Methods in Python
10
The @property Decorator in Python
11
Python Dataclasses Explained
Error Handling
01
try, except, finally in Python
02
Handling Multiple Exceptions in Python
03
Raising Custom Exceptions in Python
04
Understanding Python's Exception Hierarchy
05
Assertions in Python
File Handling
01
Reading and Writing Text Files in Python
02
Working with the with Statement in Python
03
Working with CSV Files in Python
04
Working with JSON Files in Python
05
Working with Directories (os, pathlib) in Python
Modules and Packages
01
Importing Built-in Modules in Python
02
Creating Your Own Modules in Python
03
Understanding Packages and init.py
04
Python Standard Library Overview
05
Installing Packages with pip
Advanced Core Concepts
01
Iterators and Iterables in Python
02
Context Managers in Python (with, contextlib)
03
Multithreading Basics in Python
04
Multiprocessing Basics in Python
05
Asyncio Basics: async/await in Python
06
Memory Management and Garbage Collection in Python
07
Type Hints in Python (typing module)

Type Conversion / Casting in Python

At some point, nearly every Python program needs to turn one data type into another — a string typed by a user into a number you can do math with, or a number into a string you can display. That's python type conversion, and this article covers how it works, both automatically and manually, along with the errors it commonly produces.

What is Type Conversion?

Type conversion means changing a value from one data type to another — turning a string "5" into the integer 5, or an integer 5 into the float 5.0.

Python handles this in two distinct ways:

  • Implicit conversion — Python does it automatically, behind the scenes, when it's safe to do so.

  • Explicit conversion (casting) — you deliberately convert a value yourself, using a built-in function.

Why it matters

Get type conversion wrong, or skip it when it's needed, and you'll run into one of Python's most common early errors: a TypeError from trying to combine two incompatible types, like adding a number to a string. Understanding when Python converts automatically — and when you need to do it yourself — heads off a lot of confusion.

Implicit Type Conversion

Implicit conversion happens automatically whenever Python can combine two types without losing information or guessing your intent.

The "promote to the larger type" rule

The clearest example is mixing integers and floats. Python automatically converts the integer to a float so the operation can proceed without losing precision:

result = 5 + 2.5
print(result)          # 7.5
print(type(result))    # <class 'float'>

The 5 was implicitly treated as 5.0 for the purposes of this calculation. Python follows a consistent rule here: when combining two numeric types, it "promotes" the result to whichever type can represent both values accurately — int to float, but never the other way around automatically, since converting a float to an int would silently throw away the decimal portion.

count = 3
average_score = 88.5

total = count + average_score
print(total)          # 91.5
print(type(total))    # <class 'float'>

This only works between compatible numeric types. Python won't implicitly convert a string and a number for you — that requires explicit conversion, covered next.

Explicit Type Conversion (Casting)

Explicit conversion — often called casting — is when you deliberately convert a value using one of Python's built-in constructor functions.

The core casting functions
int()       # convert to integer
float()     # convert to float
str()       # convert to string
bool()      # convert to Boolean
complex()   # convert to complex number
String to int

This is the single most common casting operation in beginner code, usually applied to user input:

age_input = "25"
age = int(age_input)
print(age + 5)   # 30
Float to int — truncation, not rounding

This trips people up often enough to call out explicitly: converting a float to an int with int() truncates the decimal portion — it does not round.

print(int(9.8))    # 9  — not 10
print(int(9.1))    # 9
print(int(-9.8))   # -9 — truncates toward zero, not "down"

If you actually want rounding behavior, use Python's built-in round() function instead:

print(round(9.8))   # 10
Number to string, for concatenation

Strings and numbers can't be combined with + directly — you have to convert the number to a string first:

age = 30
message = "You are " + str(age) + " years old"
print(message)

(Note: an f-string, as covered in the earlier article on strings, handles this more cleanly — f"You are {age} years old" — but explicit str() conversion is worth understanding on its own, since you'll still need it in non-f-string contexts.)

Casting bool to and from int

Since bool is technically a subclass of int in Python, casting between them is direct and predictable:

print(int(True))     # 1
print(int(False))    # 0
print(bool(1))        # True
print(bool(0))        # False
print(bool(-5))       # True — any nonzero number casts to True

Common Conversion Errors and How to Handle Them

ValueError from non-numeric strings

Trying to convert a string that isn't actually a valid number raises a ValueError:

int("hello")
# ValueError: invalid literal for int() with base 10: 'hello'

int("3.14")
# ValueError: invalid literal for int() with base 10: '3.14'

That second example surprises some beginners — "3.14" looks numeric, but int() can't parse a decimal point directly. You'd need to go through float() first: int(float("3.14")).

TypeError from combining incompatible types

If you skip conversion entirely and try to combine incompatible types directly, Python raises a TypeError instead:

age = 30
print("Age: " + age)
# TypeError: can only concatenate str (not "int") to str

The fix is the explicit conversion covered above: "Age: " + str(age).

Safely handling conversions with try/except

Because a python casting error like ValueError will crash your program if left unhandled, it's good practice to wrap risky conversions — especially anything coming from user input — in a try/except block:

user_input = input("Enter your age: ")

try:
    age = int(user_input)
    print(f"In 10 years, you'll be {age + 10}")
except ValueError:
    print("That doesn't look like a valid number.")

This way, a mistyped or unexpected input produces a friendly message instead of an unhandled crash.

Real-World Use Cases

Converting user input to numbers

This is the most common practical scenario for type conversion. The input() function always returns a string, no matter what the user types — so any calculation involving that input requires explicit conversion first:

price_input = input("Enter the price: ")
price = float(price_input)   # float, since prices often include decimals

tax = price * 0.08
print(f"Tax: {tax:.2f}")
Formatting numbers as strings for display

The reverse case is just as common — converting a computed number into a string so it can be combined with other text for output:

total_items = 5
message = "You have " + str(total_items) + " items in your cart"
print(message)

As mentioned earlier, f-strings handle this implicitly and are generally the cleaner choice in modern code, but the underlying concept — number to string — is the same either way.

Casting with collections

Type conversion isn't limited to numbers and strings — Python's collection types support casting too, which is worth knowing even at this early stage:

my_list = list((1, 2, 3))     # tuple to list
my_tuple = tuple([1, 2, 3])   # list to tuple
my_set = set([1, 2, 2, 3])    # list to set — automatically removes duplicates

These will make more sense once you've covered lists, tuples, and sets in detail later in this series, but it's useful to know the same casting pattern — calling the target type as a function — applies well beyond just numbers and strings.

Best practice: validate before casting

Any time you're converting data that comes from outside your program — user input, a file, an API response — treat it as untrustworthy until proven otherwise. Wrap conversions in try/except, check for expected formats before casting, and never assume external data will be exactly the type or shape you expect. This single habit prevents a large share of the crashes beginner programs run into.

PREVIOUSNEXT LESSON