Python Data types & type casting: 10 practice problems
UNIT 1 of the free Python for AI course. Read the short theory, then solve the problems below with instant tests. Python runs in your browser.
▶ Practise Data types & type casting nowAll topicsTheory: Data types & type casting in Python
THEORY
------
* Built-in types
int 42, -7, 1_000_000 unlimited size (2 ** 1000 works!)
float 3.14, 2.0, 1e-3 64-bit, APPROXIMATE: 0.1 + 0.2 == 0.30000000000000004
complex 2 + 3j .real, .imag
str "hi", 'hi', """multi""" immutable text
bool True, False subclass of int
NoneType None "no value" (functions without return give None)
list / tuple / set / dict collections (Unit 2)
* Checking types: type(x) is int isinstance(x, (int, float)) ← prefer isinstance
Gotcha: isinstance(True, int) is True (bool IS an int).
* DYNAMIC TYPING: a name can refer to any type at any time: x = 5; x = "five" (legal).
STRONG TYPING: Python won't silently mix incompatible types: "5" + 5 -> TypeError.
* TYPE CASTING (conversion)
- IMPLICIT (automatic, "widening"): int + float -> float (3 + 2.5 = 5.5), True + 1 = 2
- EXPLICIT (you do it):
int("42") -> 42 int(3.99) -> 3 (truncates toward 0) int(-3.99) -> -3
int("3.5") -> ValueError! use int(float("3.5"))
int("ff", 16) -> 255 int("1011", 2) -> 11 bin(11) -> '0b1011' hex(255) -> '0xff'
float("2.5") -> 2.5 float("inf"), float("nan") exist
str(3.0) -> "3.0" bool("") -> False bool("0") -> True bool(0) -> False
list("abc") -> ['a', 'b', 'c'] tuple([1, 2]) set([1, 1, 2]) -> {1, 2}
- input() ALWAYS returns a str -> age = int(input("Age: "))
* ROUNDING: round(2.675, 2) -> 2.67 (float can't store 2.675 exactly!)
round(2.5) -> 2, round(3.5) -> 4 ("banker's rounding": ties go to EVEN)
Compare floats with tolerance: abs(a - b) < 1e-9 or math.isclose(a, b)
* Money tip: store paise/cents as int, or use decimal.Decimal, never trust float equality.
10 Data types & type casting practice problems
1. What Type Is It? — type()
Easy1 way to solve📤 OUTPUT: return a str (text), e.g. 'int'. Use `return`, not print().
Return the type name as a string.
type_name(3) -> "int" type_name(3.0) -> "float" type_name(None) -> "NoneType"
type_name(True) -> "bool" type_name([1]) -> "list"
Hint: every type has a __name__ attribute.
Solve “What Type Is It? — type()” in your browser →2. E-commerce Price Scraper — str methods + float()
Easy2 ways to solve📤 OUTPUT: return a float, e.g. 1299.5. Use `return`, not print().
Real world: A price-comparison site reads prices like "Rs. 1,299.50" from web pages.
Remove "Rs.", commas and spaces, and return a float.
parse_price("Rs. 1,299.50") -> 1299.5 parse_price("Rs.99") -> 99.0
Solve “E-commerce Price Scraper — str methods + float()” in your browser →3. Safe Form Input — validating before casting
Easy1 way to solve📤 OUTPUT: return an int, e.g. 42. Use `return`, not print().
Real world: A form field should become an int, but users type garbage.
Return int(text) if text (after stripping spaces) is a whole number, possibly negative,
else return default. Solve it WITHOUT try/except (use str methods).
safe_int("42") -> 42 safe_int(" -7 ") -> -7 safe_int("4.2") -> 0 safe_int("abc", -1) -> -1
Solve “Safe Form Input — validating before casting” in your browser →4. Network Bits — int(x, base)
Easy3 ways to solve📤 OUTPUT: return an int, e.g. 11. Use `return`, not print().
Real world: Subnet masks and IP addresses are binary underneath.
binary_to_decimal("1011") -> 11 binary_to_decimal("11111111") -> 255
Ways: int(bits, 2) · loop: value = value * 2 + int(bit)
Solve “Network Bits — int(x, base)” in your browser →5. Decimal to Binary — bin() / format()
Easy3 ways to solve📤 OUTPUT: return a str (text), e.g. '1011'. Use `return`, not print().
Return the binary string WITHOUT the "0b" prefix. n >= 0.
decimal_to_binary(11) -> "1011" decimal_to_binary(0) -> "0"
Ways: bin(n)[2:] · f"{n:b}" · repeated % 2 and // 2 (build the string backwards)
Solve “Decimal to Binary — bin() / format()” in your browser →6. Float Comparison — precision gotcha
Easy2 ways to solve📤 OUTPUT: return a bool (True / False), e.g. True. Use `return`, not print().
Real world: A test checks 0.1 + 0.2 == 0.3 and fails! Fix it.
Return True if a and b differ by less than 1e-9.
floats_equal(0.1 + 0.2, 0.3) -> True floats_equal(1.0, 1.1) -> False
Solve “Float Comparison — precision gotcha” in your browser →7. Config File Flags — string -> bool
Easy2 ways to solve📤 OUTPUT: return a bool (True / False), e.g. True. Use `return`, not print().
Real world: Settings files say "yes", "TRUE", "on", "1" for enabled.
Return True for yes/true/on/1 (any case, spaces ignored), else False.
to_bool(" Yes ") -> True to_bool("0") -> False to_bool("False") -> False
Viva: why is bool("False") True?
Solve “Config File Flags — string -> bool” in your browser →8. Split Money Safely — float -> int rounding
Medium2 ways to solve📤 OUTPUT: return a tuple, e.g. (12, 75). Use `return`, not print().
Real world: A payment gateway needs whole rupees and paise separately.
Return a tuple (rupees, paise) of ints. amount >= 0 with at most 2 decimals.
rupees_and_paise(12.75) -> (12, 75) rupees_and_paise(0.29) -> (0, 29)
Trap: int(0.29 * 100) is 28! (0.29 * 100 == 28.999999999999996). Use round().
Solve “Split Money Safely — float -> int rounding” in your browser →9. Payments CSV Importer — interview at a payments company
Project1 way to solve📤 OUTPUT: return a dict, e.g. {'id': 17, 'amount': 1299.5, 'paid': True, 'me…. Use `return`, not print().
Interviewer: "Merchants upload CSVs typed by humans. Clean each row into proper types."
row: dict of STRINGS, e.g. {"id": " 17 ", "amount": "₹1,299.50", "paid": "Yes", "method": "upi "}
Return {"id": int,
"amount": float, or None if it isn't a number after removing ₹, commas and spaces,
"paid": True for yes / y / true / 1 (any case), else False,
"method": stripped UPPER-case text, or "UNKNOWN" if empty}
Solve “Payments CSV Importer — interview at a payments company” in your browser →10. Stage 3 — the Literal Parser (turns source text into typed values)
Compiler1 way to solve📤 OUTPUT: return the Python value (int, float, bool, None or str), e.g. 42; RAISE ValueError for bad text. Use `return`, not print().
Strip spaces, then:
integer (optional leading -) "42" -> 42 decimal "3.14" -> 3.14
true / false (any case) -> True / False none (any case) -> None
a double-quoted string '"hi"' -> "hi" (text between the quotes)
anything else -> raise ValueError(f"bad literal: {text}")
Solve “Stage 3 — the Literal Parser (turns source text into typed values)” in your browser →← BOOLEAN LOGIC (needed for if-statements and loops) Operators & operator precedence →