Python Course
Type Casting in Python
In this lesson, you will learn about Type Casting — the process of converting one data type into another. This is something every Python program needs at some point. By the end of this lesson, you will know exactly how and when to convert between integers, floats, strings, lists, tuples, and sets.
1. What is Type Casting?
Every value in Python has a data type — for example, 25 is an integer, "25" is a string, and 25.0 is a float. Sometimes you receive data in one type but need it in another. Type casting is the act of converting a value from one type into another.
A very common real-world situation: when a user types something into a form or terminal, Python receives it as a string — even if they typed a number. Before you can do any math with it, you must convert it to an integer or float. That conversion is type casting.
Where is type casting used?
- Converting user input (always a string) into a number for calculations
- Converting a price stored as a string from a database into a float
- Converting a list into a set to remove duplicates
- Converting a number into a string to display it in a sentence
- Converting between lists, tuples, and sets when the structure needs to change
2. Implicit vs Explicit Type Casting
There are two kinds of type casting in Python. Implicit casting is done automatically by Python without you asking — it happens silently in the background. Explicit casting is done by you, the programmer, by calling a conversion function.
# IMPLICIT casting — Python does it automatically
# Adding an int and a float together
a = 5 # integer
b = 2.5 # float
result = a + b
print(result) # Python quietly converts 5 to 5.0 before adding
print(type(result)) # Result is float — Python chose the "bigger" type
# EXPLICIT casting — YOU do it using a function
x = 9.99
y = int(x) # You are telling Python: convert this float to int
print(y) # Decimal part is cut off — not rounded
print(type(y))
<class 'float'>
9
<class 'int'>
What just happened?
- Python automatically converted
5to5.0before adding — this is implicit casting. You did not write any conversion code. int(9.99)cuts off everything after the decimal point — it does not round.9.99becomes9, not10.- Implicit casting always goes from a smaller type to a larger type (int → float) to avoid losing data.
3. Converting to Integer — int()
The int() function converts a value into a whole number. It works on floats (removes the decimal), strings that contain a whole number, and booleans. It does not work on strings that contain decimals or letters.
# Converting different types to integer
print(int(7.9)) # float → int : decimal is removed (not rounded)
print(int("50")) # string → int : works if string holds a whole number
print(int(True)) # bool → int : True becomes 1
print(int(False)) # bool → int : False becomes 0
# This will cause an error — can't convert a decimal string directly
try:
print(int("12.5"))
except ValueError as e:
print("Error:", e)
50
1
0
Error: invalid literal for int() with base 10: '12.5'
What just happened?
int(7.9)gives7— the.9is simply dropped. Python does not round up.int("50")works because the string contains only digits.int("12.5")fails because it has a dot — useint(float("12.5"))in that case.TrueandFalseconvert to1and0— this is because booleans are actually a subtype of integer in Python.
4. Converting to Float — float()
The float() function converts a value into a decimal number. It works on integers, numeric strings (including decimal ones), and booleans.
# Converting different types to float
print(float(10)) # int → float : adds .0
print(float("3.14")) # string → float : works with decimal strings
print(float("100")) # string → float : works with whole number strings too
print(float(True)) # bool → float : True becomes 1.0
print(float(False)) # bool → float : False becomes 0.0
3.14
100.0
1.0
0.0
What just happened?
float(10)simply adds a decimal point —10becomes10.0.float("3.14")works because the string is a valid decimal number. If the string contained letters, it would raise aValueError.- Unlike
int(),float()can handle strings with decimal points — sofloat("12.5")works perfectly.
5. Converting to String — str()
The str() function converts any value into a string. This is used constantly when you want to combine a number with text — you cannot concatenate a string and a number directly in Python without converting first.
# Converting different types to string
print(str(100)) # int → string
print(str(3.99)) # float → string
print(str(True)) # bool → string
# Real-world use: joining a number into a sentence
age = 22
message = "You are " + str(age) + " years old."
print(message)
# Without str(), this would crash with a TypeError
# print("You are " + age + " years old.") ← this fails
3.99
True
You are 22 years old.
What just happened?
str(100)turns the number into the text"100"— they look the same but behave differently. A string cannot do math; an integer can.- Without
str(age), trying to join a number and a string with+would crash with aTypeError. - A cleaner modern alternative is an f-string:
f"You are {age} years old."— no conversion needed. Both approaches are valid.
6. Converting to Boolean — bool()
The bool() function converts a value to either True or False. Python has a simple rule: empty or zero values are False, everything else is True. Knowing this rule will help you write much cleaner conditional logic.
# Values that become FALSE
print(bool(0)) # zero integer → False
print(bool(0.0)) # zero float → False
print(bool("")) # empty string → False
print(bool([])) # empty list → False
print(bool(None)) # None → False
# Values that become TRUE
print(bool(1)) # any non-zero number → True
print(bool(-5)) # negative numbers too → True
print(bool("hi")) # any non-empty string → True
print(bool([1,2])) # any non-empty list → True
False
False
False
False
True
True
True
True
What just happened?
- Any value that is zero, empty, or
Noneconverts toFalse. Everything else isTrue. - This is called truthiness in Python. It is used in
ifstatements all the time — for example,if username:checks if the string is non-empty without needing== "". - Even
-5isTrue— only the number0is falsy, not negative numbers.
7. Converting Between Collections — list(), tuple(), set()
You can freely convert between lists, tuples, and sets using their built-in functions. This is extremely useful — for example, converting a list to a set to remove duplicates, then back to a list to sort it.
# Start with a list that has duplicates
tags = ["python", "coding", "python", "tutorial", "coding"]
print("Original list :", tags)
# Convert list → set (removes duplicates automatically)
unique = set(tags)
print("As set :", unique)
# Convert set → list (now you can sort and index it)
clean_list = list(unique)
print("Back to list :", clean_list)
# Convert list → tuple (makes it immutable / fixed)
fixed = tuple(tags)
print("As tuple :", fixed)
# Convert tuple → list (makes it editable again)
editable = list(fixed)
print("Tuple to list :", editable)
As set : {'coding', 'python', 'tutorial'}
Back to list : ['coding', 'python', 'tutorial']
As tuple : ('python', 'coding', 'python', 'tutorial', 'coding')
Tuple to list : ['python', 'coding', 'python', 'tutorial', 'coding']
What just happened?
set(tags)instantly removed"python"and"coding"duplicates — the cleanest way to deduplicate a list.list(unique)converts it back so you can sort, index, and work with it normally.tuple(tags)creates an immutable version — great for data that should not be changed after this point.
8. Real-World Example — Handling User Input
The most common place you will use type casting in real programs is when handling user input. The input() function in Python always returns a string — even if the user types a number. You must cast it before doing any calculations.
# Simulating what input() gives you — always a string
price_str = "250" # imagine user typed this
quantity_str = "4" # imagine user typed this
# These are strings — you cannot multiply strings like numbers
# price_str * quantity_str would give an error
# Cast both to integers first
price = int(price_str)
quantity = int(quantity_str)
total = price * quantity
print("Price :", price)
print("Quantity :", quantity)
print("Total :", total)
# Adding tax — cast to float for decimal precision
tax_rate = float("0.18") # 18% GST
tax_amount = total * tax_rate
final_price = total + tax_amount
print("Tax (18%):", tax_amount)
print("Final :", final_price)
Quantity : 4
Total : 1000
Tax (18%): 180.0
Final : 1180.0
What just happened?
"250"and"4"are strings — you cannot do math on them until they are cast toint.- After casting,
price * quantityworks correctly and gives1000. float("0.18")converts the tax rate string into a decimal number for precise multiplication.- This exact pattern — cast input, do math, display result — is used in every billing, calculator, and form-processing program.
9. Checking a Value's Type Before Casting
Before casting a value, it is good practice to check what type it currently is. Python gives you two tools for this: type() which tells you the type, and isinstance() which checks if a value belongs to a specific type and returns True or False.
value = "42"
# type() — tells you what type a value is
print(type(value)) #
# isinstance() — checks if it matches a specific type
print(isinstance(value, str)) # True — it IS a string
print(isinstance(value, int)) # False — it is NOT an integer
# Practical pattern: only cast if needed
if isinstance(value, str):
value = int(value) # safe to cast now
print("After cast:", value)
print("New type :", type(value))
True
False
After cast: 42
New type : <class 'int'>
What just happened?
type(value)prints the full type name — useful for debugging and understanding what you are working with.isinstance(value, str)returnsTrueorFalse— better for writing conditions because you can use it directly in anifstatement.- The pattern
if isinstance(...): castis the professional way to safely convert values — you only convert when you are sure it is the right type to begin with.
10. Common Casting Errors to Avoid
Type casting fails when the value cannot logically be converted. These errors are very common for beginners — knowing them in advance will save you a lot of debugging time.
# ERROR 1: Converting a word string to int or float
try:
print(int("hello"))
except ValueError as e:
print("Error 1:", e)
# ERROR 2: Converting a float string directly to int
try:
print(int("9.5")) # must convert to float first, then int
except ValueError as e:
print("Error 2:", e)
# CORRECT way to handle Error 2
print("Correct:", int(float("9.5")))
# ERROR 3: Converting None to int
try:
print(int(None))
except TypeError as e:
print("Error 3:", e)
Error 2: invalid literal for int() with base 10: '9.5'
Correct: 9
Error 3: int() argument must be a string, a bytes-like object or a real number, not 'NoneType'
What just happened?
int("hello")fails with aValueError— Python cannot turn a word into a number.int("9.5")also fails — even though it looks numeric, it has a decimal point. The fix is to chain the casts:int(float("9.5"))— first convert to float, then to int.int(None)fails with aTypeError—Nonemeans "no value at all" and cannot be cast to anything.
11. Lesson Summary
A complete reference of every conversion covered in this lesson.
| Function | Converts To | Example | Result |
|---|---|---|---|
| int() | Integer | int("10"), int(3.9) | 10, 3 |
| float() | Float | float(5), float("3.14") | 5.0, 3.14 |
| str() | String | str(99), str(3.5) | "99", "3.5" |
| bool() | Boolean | bool(0), bool("hi") | False, True |
| list() | List | list((1,2,3)) | [1, 2, 3] |
| tuple() | Tuple | tuple([1,2,3]) | (1, 2, 3) |
| set() | Set | set([1,1,2,3]) | {1, 2, 3} |
| int(float()) | Int from decimal string | int(float("9.5")) | 9 |
| type() | Check type | type("hello") | <class 'str'> |
🧪 Practice Questions
Answer based on what you learned in this lesson.
1. What function converts a string like "42" into a whole number?
2. What does int(7.9) return?
3. What does bool(0) return?
4. Which function do you use to join a number into a text sentence using +?
5. What error is raised when you try to run int("hello")?
🎯 Quiz — Test Your Understanding
Q1. What is the result of int(9.99)?
Q2. What does bool("hello") return?
Q3. When Python automatically converts an int to a float during addition, this is called __________ casting.
Q4. What is the correct way to convert the string "9.5" to an integer?
Q5. What does int(True) return?