Rana Maninder Singh
Lesson 3 of 9Python basics

Python Data Types

Lesson opener

In one line: Core scalar types: int, float, str, bool, None.

Why it matters: Each value has a type that determines what operations make sense on it.

Before this lesson: Variables

Before you start

ResourceLink
PreviousVariables
NextOperators


What you will learn

  • Core scalar types: int, float, str, bool, None
  • Implicit vs explicit typecasting — why Python sometimes converts types without asking
  • Every conversion function (int, float, str, bool) with success and failure cases
  • Truthy and falsy — what if statements actually check (including bool([0]) vs bool([]))
  • Common data-work bugs: string repetition, TypeError from mixed types, and why blind conversion is risky (ValueError vs TypeError)
Python data type cheat sheet
Python data type cheat sheet

Built-in types

[Core scalar types]

WHY: Each value has a type that determines what operations make sense on it.

WHEN: You're storing mixed customer fields — counts, money, names, flags, and missing values.

n = 42          # int
price = 19.99   # float
name = "Rana"   # str
flag = True     # bool
missing = None  # NoneType

Breaking it down:

Use this when: modeling a single customer record before building a DataFrame.


Section 1 — Implicit vs explicit typecasting

Plain English:

Python sometimes converts types for you without asking. That is implicit typecasting. You do it yourself with a function like int() or float() — that is explicit typecasting. Knowing the difference stops you from being confused by results you did not ask for.

Implicit examples

[Mixed arithmetic promotes int to float]

WHY: When you mix int and float, Python picks the wider type so nothing is lost.

WHEN: Any calculation mixing whole numbers and decimals.

# Python promotes int to float automatically in mixed arithmetic
result = 5 + 2.0
print(result)       # 7.0 — not 7
print(type(result)) # <class 'float'> — not int

Boolean arithmetic (surprises everyone)

print(True + 5)     # 6
print(False + 10)   # 10
print(True * 100)   # 100
# Why: True == 1, False == 0 in Python
# bool is a subclass of int — implicit promotion in math

Breaking it down:

Use this when: debugging why a calculation returned 7.0 instead of 7, or why True + 1 equals 2.


Section 2 — Explicit conversion: success and failure

[Inspect types with type()]

WHY: Before you convert, confirm what you actually have — especially from CSV or user input.

WHEN: A script crashes on row 47 and you need to see if the field is str or int.

type(42)          # <class 'int'>
type("42")        # <class 'str'>

int() — what works and what breaks

int(3.9)        # → 3 (truncates toward zero — NOT rounds)
int("42")       # → 42 (works)
int("3.14")     # → ValueError! (fails — decimal point in string)
int(True)       # → 1
int(False)      # → 0

# The fix for "3.14":
int(float("3.14"))  # → 3 (float first, then int)

Breaking it down:

float()

float(5)        # → 5.0
float("3.14")   # → 3.14 (works)
float("hello")  # → ValueError!
float(True)     # → 1.0

str() — almost never fails

str(42)         # → "42"
str(3.14)       # → "3.14"
str(True)       # → "True" (capital T — not "true")
str([1, 2, 3])  # → "[1, 2, 3]" (text representation of the list)

bool() — truthy and falsy

This is what if statements actually check.

bool(0)         # → False
bool(1)         # → True
bool(-99)       # → True (any non-zero number)
bool("")        # → False (empty string)
bool("hello")   # → True
bool([])        # → False (empty list)
bool([0])       # → True (list has one item — even though that item is 0)
bool(None)      # → False

The single most important rule for data filtering: bool([0]) is True because the list is not empty. Python checks whether the container has items, not whether the items inside are truthy. Empty [] is False; any non-empty list is True.

Use this when: filtering DataFrame rows, checking if user input exists, or validating API responses before processing.


Section 3 — Truthy and falsy table

Valuebool() resultWhy
0FalseZero is falsy
0.0FalseZero float too
""FalseEmpty string
[]FalseEmpty list
{}FalseEmpty dict
()FalseEmpty tuple
NoneFalseNothing
Everything elseTrueNon-zero numbers, non-empty strings, non-empty collections
# Why this matters in real code:
user_input = ""

# Without knowing truthy/falsy:
if user_input == "":     # works but verbose
    print("No input")

# With truthy/falsy knowledge:
if not user_input:       # cleaner, Pythonic
    print("No input")

# Real data example:
data = []
if not data:
    print("No records to process")

Breaking it down:

Use this when: guard clauses at the top of a data pipeline — skip processing when there is nothing to work with.


Section 4 — Common mistake: type mismatch in operations

Plain English: This is the most common beginner bug in data work — values look like numbers but are still strings.

# TypeError — string minus integer:
age_str = "25"     # came from user input or CSV
birth_year = 2026 - age_str
# TypeError: unsupported operand type(s) for -: 'int' and 'str'

# Fix:
birth_year = 2026 - int(age_str)  # 2001
# String repetition — not multiplication:
price = "1500"
quantity = 3
total = price * quantity
print(total)  # "150015001500" — string repeated 3 times!

# Fix:
total = int(price) * quantity  # 4500
CodeWhat happensFix
2026 - "25"TypeError2026 - int("25")
"1500" * 3"150015001500"int("1500") * 3
int("3.14")ValueErrorint(float("3.14"))
float("N/A")ValueErrorCheck before casting

Use this when: any field from input(), a CSV, or an API might still be text when you need math.


Section 5 — Safe conversion pattern

Never convert dirty data blindly. When a value might be "N/A", blank, or the wrong kind of object, a bare int() / float() can stop the whole script. Know what fails before you learn how to catch it.

# Clean values — explicit conversion is fine:
int("42")           # → 42
float("19.99")      # → 19.99
int(float("3.14"))  # → 3  (decimal string → float → int)

# Dirty / wrong values — these raise errors (do not run them yet):
# int("hello")      # ValueError — right kind of input for int(), bad content
# int("3.14")       # ValueError — decimal point is not allowed in int("...")
# float("N/A")      # ValueError — non-numeric content
# int(None)         # TypeError — wrong type entirely for this conversion

Breaking it down:

Use this when: deciding whether a CSV cell is safe to cast, or diagnosing why a conversion blew up.


Section 6 — eval() security warning

eval() can run any Python expression. That makes it a powerful typecaster — and a dangerous backdoor if fed user input.

# eval() executes ANY Python expression
# Never use eval() on user input in a real application:

# user_input = "__import__('os').system('rm -rf /')"
# eval(user_input)  # DANGEROUS — can run shell commands

# Safe alternatives:
age = int(input("Enter age: "))           # for numbers
# json.loads(input("Enter JSON: "))       # for data structures (import json)

# Only use eval() for:
# - Quick calculations in a notebook you control
# Never in: web apps, APIs, or any code accepting external input

Prefer int(), float(), json.loads(), or your own parsers — not eval() on strings from people or files you do not trust.


From CSV row (concept)

[Casting string fields from a CSV row]

WHY: Exported spreadsheets store numbers as text — cast before comparisons or sums.

WHEN: You read a revenue cell as "914.35" and need it as a float for threshold checks.

revenue = float("914.35")
churned = int("0")

Breaking it down:

Use this when: parsing a single CSV row in a validation script.

Preview pandas dtypes in notebook:

[Checking column dtypes in pandas]

WHY: Pandas tracks types per column — preview before assuming everything is numeric.

WHEN: You loaded a CSV and want to spot columns stuck as object/string.

import pandas as pd
pd.read_csv("data/customers.csv").dtypes

Breaking it down:

Use this when: first pass on a new dataset to plan type fixes.


Common type errors (quick reference)

Plain English: Python raises TypeError when you combine types that do not fit — like adding a string to a number without converting first.

revenue = "914.35"
# revenue + 100          # TypeError: can only concatenate str (not "int") to str

revenue_num = float(revenue)
total = revenue_num + 100   # works — 1014.35

Use this when: a script crashes on one bad row — print type(field) before you math it.


Essential commands

Command / actionWhat it does
type(x)Return the type of a value.
int(x)Convert to integer — truncates floats; fails on "3.14" strings.
float(x)Convert to decimal — fails on non-numeric strings.
str(x)Convert to string — almost always succeeds.
bool(x)Truthy/falsy test — empty containers are False; bool([0]) is True.
int(float("3.14"))Safe path for decimal strings → int.
NoneRepresents missing value in Python.
.dtypesPandas column types on a DataFrame.

Practice

Before you code, fill the three blanks — Input → Logic → Output (see the worked model in py1).

Do this now: Script demonstrating 4 types + 3 conversions; print types.

Input: ___

Logic: ___

Output: ___

# Input Data


# Logic


# Output

Checklist

  • [ ] type() used to inspect values before converting
  • [ ] Can you explain the difference between implicit and explicit typecasting?
  • [ ] Can you explain why int("3.14") fails but int(float("3.14")) works?
  • [ ] Can you list 4 values that bool() converts to False?
  • [ ] Do you know what True + 5 returns and why?
  • [ ] Do you know why bool([]) is False but bool([0]) is True?
  • [ ] Can you fix "1500" * 3 and 2026 - "25" type bugs?
  • [ ] Can you explain why blind conversion is risky, and name the two error types that can result?
  • [ ] Read dtypes from CSV
  • [ ] I can explain TypeError vs ValueError and fix a str+int mistake

Interview Prep — Skill Mastery Challenge

Before you attempt these questions:

  • Review the lesson material above
  • Try to answer verbally first — as if in a real interview
  • Then reveal the answer
  • Identify any gaps and re-read that section