⚡0 XP🔥0

Type Casting (Type Conversion)

Lesson 6 of 33 ⏱ 4 min read ✎ 3 exercises ❓ 5-question quiz ▶ Runs Python

Convert values between int, float, str and bool - implicit vs explicit conversion, common errors and real-world uses.

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:

▶ Try it YourselfPython
Ctrl + Enter to run

But Python will not automatically mix numbers and strings:

age = 20
print("Age: " + age)
Output
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#

▶ Try it YourselfPython
Ctrl + Enter to run

Number to string#

▶ Try it YourselfPython
Ctrl + Enter to run
Tip

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#

▶ Try it YourselfPython
Ctrl + Enter to run
हिंदी में समझें

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
▶ Try it YourselfPython
Ctrl + Enter to run

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
Common Mistake

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#

▶ Try it YourselfPython
Ctrl + Enter to run

Summary#

  • Implicit: Python converts int → float automatically in arithmetic.
  • Explicit: use int(), float(), str(), bool(), list(), tuple(), set().
  • int() truncates decimals; use round() to round.
  • Falsy values: 0, 0.0, "", empty collections, None.
  • Invalid conversions raise ValueError.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Add numbers stored as text

The variables a and b contain numbers as strings. Convert them and print their sum as a number.

Expected output:
425
2

Build a message

Using the variables below, print exactly You scored 92 out of 100 by converting the numbers to strings and joining with +.

Expected output:
You scored 92 out of 100
3

Price to whole rupees

price = "499.75" is a string. Convert it to a float, store it in price_float, then store its whole-rupee part (without rounding) in rupees as an int. Print rupees.

Expected output:
499

Quick Quiz

Q1.

What is int("45") + 5?

Q2.

What is int(9.99)?

Q3.

What happens with int("12.5")?

Q4.

What is bool("") (an empty string)?

Q5.

What is the type of 5 + 2.0?