1.2.4Introduction to Programming (Python)

Data types — int, float, str, bool, NoneType

1,776 words8 min readdifficulty · medium5 backlinks

The five core built-in types

HOW you ask Python: the built-in type(x) returns the type object.

type(7)        # <class 'int'>
type(3.14)     # <class 'float'>
type("hi")     # <class 'str'>
type(True)     # <class 'bool'>
type(None)     # <class 'NoneType'>
Figure — Data types — int, float, str, bool, NoneType

WHY do floats behave weirdly? (Derive it)

A float is stored as (1)s×m×2e(-1)^s \times m \times 2^{e} where the mantissa mm is binary. To store a decimal like 0.10.1, Python must write it as a sum of powers of two:

0.1=kbk2k,bk{0,1}0.1 = \sum_{k} b_k\, 2^{-k}, \qquad b_k \in \{0,1\}

But 0.10.1 in binary is the infinite repeating fraction 0.000110011001120.0001100110011\ldots_2. The hardware keeps only 52 mantissa bits, so it rounds. That tiny rounding is why:

0.1 + 0.2 == 0.3      # False!
0.1 + 0.2             # 0.30000000000000004

The fix (WHAT to do instead): never test floats with ==; check closeness: ab<ε|a-b| < \varepsilon

abs((0.1 + 0.2) - 0.3) < 1e-9   # True

bool is secretly an int (Steel-man this surprise)

isinstance(True, int)   # True
True + True             # 2
["a","b","c"][True]     # 'b'  (index 1)

Truthiness — every object is usable in if. The rule (WHAT is "falsy"):


NoneType — the "nothing" value

def greet(name):
    print("Hi", name)     # prints but has no return statement
 
x = greet("Sam")
x            # None
x is None    # True  (always use 'is', never '==')

Type conversion (casting): WHAT, WHY, HOW

You can convert between types using the type name as a function. WHY: input from users always arrives as str; to do math you must convert.

int("42")      # 42      str -> int
int(3.9)       # 3       float -> int  (TRUNCATES toward zero, no rounding!)
float("3.14")  # 3.14
str(99)        # '99'
bool("")       # False   bool(0) -> False, bool("x") -> True
int("3.5")     # ERROR: not a valid int string

Common mistakes (Steel-man + fix)


Recall Explain it to a 12-year-old (hidden — try first!)

Imagine labeled boxes. A box labeled int can only hold whole apples (3 apples). A float box holds parts of an apple too (2.5 apples) but it's a slightly fuzzy measuring cup — it sometimes says 0.30000001 instead of 0.3. A str box holds beads on a string (letters). A bool box holds a light switch: ON (True=1) or OFF (False=0). And None is an empty box that you put there on purpose to say "nothing lives here yet". The label on the box decides what you're allowed to do with what's inside.


Flashcards

What does type(x) return?
The type object (class) of x, e.g. <class 'int'>.
Why is 0.1 + 0.2 != 0.3 in Python?
Floats are stored as finite binary (IEEE-754); 0.1 has no exact binary form, so rounding makes the sum 0.30000000000000004.
How should you compare two floats for equality?
With a tolerance: abs(a-b) < 1e-9 (or math.isclose), never ==.
What integer values do True and False equal?
True == 1, False == 0; bool is a subclass of int.
What does int(3.99) give and why?
3int() truncates toward zero, it does not round.
Which values are "falsy" in Python?
0, 0.0, "", None, and empty []/{}/().
What is NoneType and how many None objects exist?
The type of None, meaning "no value"; there is exactly one singleton None.
Why use x is None instead of x == None?
None is a unique singleton; is checks identity and can't be fooled by overloaded __eq__.
What does a function with no return statement return?
None.
Why does int("3.5") raise an error but int(3.5) works?
"3.5" is not a valid integer string literal; convert via int(float("3.5")).
What does "4" + "7" produce?
"47" — string concatenation, not addition.

Connections

  • Variables and assignment — types are attached to values, names just point to them.
  • Operators and operator overloading+ means add for int, concatenate for str.
  • input() and user I/O — input is always str; casting is mandatory.
  • IEEE-754 floating point — the deep reason floats are imprecise.
  • Truthiness and conditionals — how non-bool values behave in if.
  • Type checking — isinstance vs type — robust type tests.

Concept Map

interpreted by

defines

defines

defines

defines

defines

reveals

binary rounding

fix

subclass of

True=1 False=0

means

Bits 0 and 1

Data type = interpretation rule

int whole numbers

float IEEE-754

str char sequence

bool True False

NoneType single None

type&(x&) and isinstance

0.1+0.2 != 0.3

compare with abs diff less than epsilon

sum counts truthy

no value placeholder

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Dekho, Python me har value ka ek data type hota hai — yeh basically rule hai jo batata hai ki value kya hai aur uspe kaunse operations legal hain. Paanch core types hain: int (poore numbers jaise 7), float (decimal wale jaise 3.14), str (text jaise "hello"), bool (sirf True ya False), aur NoneType (jiska matlab "kuch bhi nahi"). Type check karne ke liye type(x) use karo.

Ek bahut important cheez: float thoda imprecise hota hai. Computer numbers ko binary me store karta hai, aur 0.1 ka exact binary form nahi banta, isliye 0.1 + 0.2 ka answer 0.3 nahi balki 0.30000000000000004 aata hai. Isiliye floats ko kabhi == se compare mat karo — hamesha abs(a-b) < 1e-9 use karo. Yeh galti exams aur interviews dono me bahut puchi jaati hai.

Doosri mazedaar baat: bool actually int ka chhota bhai haiTrue ka matlab 1 aur False ka matlab 0. Isliye True + True se 2 aata hai, aur sum([True, False, True]) se aap count kar sakte ho kitne conditions True hain. Aur None ek special "khaali" value hai — jab koi function return nahi karta to woh None deta hai. None check karne ke liye hamesha x is None likho, == None nahi, kyunki None pure Python me bas ek hi hota hai.

Casting bhi yaad rakho: input() se aane wala data hamesha str hota hai, to math karne se pehle int() ya float() se convert karna zaroori hai. Aur int(3.9) se 3 aata hai kyunki yeh truncate karta hai, round nahi. Bas itna pakka karlo, toh data types ka 80% concept clear ho jayega.

Test yourself — Introduction to Programming (Python)

Connections