What is type casting?#
Type casting (or type conversion) means changing a value from one data type to another - for example, turning the text "25" into the number 25.
Why do we need it? Because data often arrives in the wrong type:
input()always gives you text, even if the user types a number.- Data from files, Excel sheets and websites usually comes as text.
- To join a number with text in a message, you need to convert the number to text.
There are two kinds of conversion: implicit (automatic) and explicit (you do it).
Implicit conversion (automatic)#
Python automatically converts a "smaller" type to a "bigger" one when mixing numbers, so no data is lost:
But Python will not automatically mix numbers and strings:
age = 20
print("Age: " + age)
TypeError: can only concatenate str (not "int") to str
Explicit conversion (casting)#
You convert values yourself using these built-in functions:
| Function | Converts to | Example | Result |
|---|---|---|---|
int(x) |
integer | int("42"), int(7.9) |
42, 7 |
float(x) |
decimal number | float("3.5"), float(4) |
3.5, 4.0 |
str(x) |
string | str(100), str(2.5) |
"100", "2.5" |
bool(x) |
True/False | bool(0), bool("hi") |
False, True |
list(x) |
list | list("abc") |
['a', 'b', 'c'] |
tuple(x) |
tuple | tuple([1, 2]) |
(1, 2) |
set(x) |
set | set([1, 1, 2]) |
{1, 2} |
String to number#
Number to string#
Instead of converting with str() and +, you can use f-strings: print(f"Your roll number is {roll_no}"). You'll learn these in the Input/Output lesson - they're the modern, preferred way.
float to int - truncation, not rounding#
int() decimal वाला हिस्सा काट देता है (truncate करता है), round नहीं करता। इसलिए int(7.9) का जवाब 8 नहीं बल्कि 7 है। अगर आपको सही rounding चाहिए तो round() function इस्तेमाल करें।
Converting to bool - truthy and falsy values#
bool() returns False for "empty" or "zero" values and True for everything else.
Falsy (become False) |
Truthy (become True) |
|---|---|
0, 0.0 |
any non-zero number: 5, -1, 0.1 |
"" (empty string) |
any non-empty string: "a", " ", "False" |
[], (), {}, set() |
any non-empty collection |
None |
Errors you will meet#
int("abc") # ValueError: invalid literal for int() with base 10: 'abc'
int("12.5") # ValueError - decimal point in the text
int("") # ValueError - empty text
To convert "12.5" to an int, go through float first:
print(int(float("12.5"))) # 12
int(" 25 ") works (spaces at the ends are ignored), but int("2 5") and int("25kg") fail. Clean your data first - you'll learn .strip() and .replace() in the String Methods lesson.
Real-world example#
Summary#
- Implicit: Python converts int → float automatically in arithmetic.
- Explicit: use
int(),float(),str(),bool(),list(),tuple(),set(). int()truncates decimals; useround()to round.- Falsy values:
0,0.0,"", empty collections,None. - Invalid conversions raise
ValueError.