๐ฆ What is Type Casting?
Type casting is converting data from one type to another. Python does some conversions automatically (implicit), but often you must tell it explicitly with functions like int(), float(), or str().
When you read CSV files, form inputs, or API responses, data arrives as strings. To do math on them, you must cast them to numbers. Get the type wrong, and Python raises ValueError.
This lesson covers 5 casting functions, the traps that cause errors, and how to handle them safely.
๐ฏ The 5 Core Casting Functions
๐ฆ The Business Scenario
SouthBank India exports daily transactions to CSV: amounts are stored as text strings ("โน177,500.00", "โน45,200.50"). Before processing payments, the system must convert these strings to floats for calculations. One mistake โ like trying to convert "45.67" directly with int() โ crashes the entire batch.
๐ป Step 1: Read CSV Strings and Convert to Float
CSV files store everything as strings. Here's how to safely extract the amount and convert it:
โ ๏ธ Step 2: Handle ValueError with Try-Except
When int() receives a decimal string, it fails. You must use try-except to catch and handle the error:
โฆ Step 3: Understand Bool Truthiness
Any value in Python can be cast to bool. These are the truthiness rules โ which values count as True vs False:
๐ Step 4: Chain Conversions Safely
Sometimes you need multiple casts. Convert strings to float first, then to int to drop decimals:
๐ข Where You'll Use Type Casting
๐ค AI & Type Casting
Every Machine Learning Model Uses Type Casting
When training a fraud-detection model, raw CSV data (strings) must be cast to numbers. NumPy arrays require float64 types. Text labels are one-hot encoded into boolean arrays. Type casting is the invisible first step in every AI pipeline โ without it, the model never runs.
Examples:
pd.astype("float32") np.array(..., dtype=bool) int(pred > 0.5) str.split() โ intโก Mini Challenge
Given this CSV row:
payment_row = "TXN123,โน5000.00,Pending"
Extract the amount, convert it to float, and calculate 18% GST. Print the net amount after tax.
split(",") to break the row, then replace("โน", "") to clean, then float() to convert.๐ฌ Interview Questions
int() or float(). Explicit casting is safer because you control it and can catch errors.
int() expects a string with no decimal point. The string "3.5" contains a dot, so Python raises ValueError. Use int(float("3.5")) instead โ convert to float first, then drop the decimal.
False, 0, 0.0, None, "", [], {}, () โ empty containers and zero values. All others are truthy. This matters when you cast to bool or use values in if statements.
ValueError. Example: try: int(user_input) except ValueError: print("Invalid"). Always validate before processing.
๐ฏ Test Your Knowledge
๐ Type Casting Cheatsheet
| Function | Input | Output | Common Use |
|---|---|---|---|
int() |
"123", 45.9, True | 123, 45, 1 | String โ whole number, drops decimals |
float() |
"45.67", 45, True | 45.67, 45.0, 1.0 | String โ decimal number |
str() |
123, 45.6, True | "123", "45.6", "True" | Number/bool โ text for display |
bool() |
0, "", None, [] | False, False, False, False | Any value โ True/False |
list() |
"abc", (1,2), {1,2} | ['a','b','c'], [1,2], [1,2] | Other iterables โ list |
tuple() |
[1,2], "ab", {1,2} | (1,2), ('a','b'), (1,2) | Other iterables โ immutable tuple |
set() |
[1,1,2], "aab", (1,2) | {1,2}, {'a','b'}, {1,2} | Remove duplicates |
โ ๏ธ Common Mistakes
int("3.5") โ ValueError. Fix: int(float("3.5")) or handle with try-except.user_input = "", then if user_input is False, even though the variable exists. Check explicitly: if user_input is not None and user_input != "".float("โน100.50") fails. Use float("โน100.50".replace("โน", "")) first.bool("0") is True because the string is non-empty. Only bool(0) is False. This confuses string "0" with the integer 0.โฆ Key Takeaways
- Type casting converts data from one type to another using functions like
int(),float(),str(),bool(). - CSV and user input arrive as strings; always cast to numbers before doing math or comparisons.
int("3.5")fails because int() cannot parse decimals. Useint(float("3.5"))instead.- Handle casting errors safely with try-except blocks to validate user input.
- Falsy values (0, "", None, [], empty containers) are critical for truthiness checks in conditionals.
- Every machine learning pipeline starts with casting raw CSV data to numeric arrays.
Ready to go further?
Join the Best AI Program: The AI-Era Analyst โ 5 months, fully online, with placement assistance. Week 1 is free.
Explore The AI-Era Analyst โ