๐Ÿ“ฆ 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().

int("123") โ†’ 123

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

int()
int("123")
Cast to whole number. Drops decimals.
float()
float("45.67")
Cast to decimal number.
str()
str(123)
Cast to text/string.
bool()
bool(1)
Cast to True/False.
list/tuple/set
list("abc")
Cast to container types.

๐Ÿฆ The Business Scenario

๐Ÿฆ
Banking ยท SouthBank India
Converting CSV Transaction Amounts

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.

10K+
Txns per day
3
Casting steps
โ‚น
At stake per error

๐Ÿ’ป 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:

csv_to_float.py โ–ถ Run to see output below
# Output Raw amount: โ‚น177500.50 (type: str) Converted: 177500.5 (type: float) Tax (5%): โ‚น8875.02 Net: โ‚น169625.48

โš ๏ธ 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:

handle_error.py โ–ถ Run to see output below
# Output Error: Cannot convert '25.5' to int Reason: invalid literal for int() with base 10: '25.5' Fallback worked: 25 --- The Right Way --- Amount (rounded down): 3500

โœฆ 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:

truthiness.py โ–ถ Run to see output below
# Output FALSY VALUES (bool() โ†’ False): bool('') = False bool(0) = False bool(0.0) = False bool(None) = False bool([]) = False bool({}) = False bool(()) = False TRUTHY VALUES (bool() โ†’ True): bool('0') = True bool(1) = True bool(-1) = True bool([0]) = True bool({'a': 1}) = True No balance found โ€” account pending setup

๐Ÿ”— Step 4: Chain Conversions Safely

Sometimes you need multiple casts. Convert strings to float first, then to int to drop decimals:

chained_casting.py โ–ถ Run to see output below
# Output Original: 3500.75 (str) โ†’ float(): 3500.75 โ†’ int(): 3500 You are 28 years old Prices as strings: ['100', '250', '500']

๐Ÿข Where You'll Use Type Casting

๐Ÿฆ
Banking & Fintech
CSV exports โ†’ float for calculations, user input โ†’ int for account pins
๐Ÿ“ฑ
Mobile Apps (M-Pesa, UPI)
Form fields arrive as strings, must cast to numbers before processing transfers
๐Ÿ“Š
Data Science & Analytics
Pandas reads CSV as strings, you cast to int/float for machine learning
๐ŸŒ
Web APIs
JSON responses contain numbers as strings; cast before arithmetic

๐Ÿค– 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

Parse a CSV payment row and calculate tax

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.

Use split(",") to break the row, then replace("โ‚น", "") to clean, then float() to convert.

๐Ÿ’ฌ Interview Questions

Implicit: Python converts automatically (e.g., int + float โ†’ float). Explicit: You call a function like 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.
Use try-except to catch ValueError. Example: try: int(user_input) except ValueError: print("Invalid"). Always validate before processing.
ML frameworks (NumPy, TensorFlow) require numeric arrays. Models compute dot products and gradients โ€” operations only defined on numbers, not strings. CSV data is text by default; you must cast it to float64 (or int32) for the mathematical operations to work.

๐ŸŽฏ Test Your Knowledge

Question 1 of 5
What does int("42") return?
Question 2 of 5
Why does int("3.14") fail?
Question 3 of 5
Which of these is falsy?
Question 4 of 5
To safely convert "45.67" to an integer, you should use:
Question 5 of 5
What is the correct way to handle user input safely?
0
/5
Great effort!

๐Ÿ“‹ 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

Using int() on a decimal string
int("3.5") โ†’ ValueError. Fix: int(float("3.5")) or handle with try-except.
Forgetting that empty strings are falsy
If user_input = "", then if user_input is False, even though the variable exists. Check explicitly: if user_input is not None and user_input != "".
Not removing symbols before casting
float("โ‚น100.50") fails. Use float("โ‚น100.50".replace("โ‚น", "")) first.
Assuming bool("0") is False
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. Use int(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.
Africa & India's Best AI Academy
๐Ÿค– AI-first ๐ŸŽ“ Placement Assistance

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 โ†’