Python’s three everyday data types: numbers for math, strings for text, booleans for decisions. Use type(x) to check any value’s type.
Numbers
- int: whole numbers (
-3,42); never overflow. - float: numbers with a decimal point (
3.5,2.0); binary approximations. 2is an int;2.0is a float, even though same quantity.- A variable names a value;
=is assignment (not math equals).
Arithmetic operators
+ - *standard;/true division, always a float (6 / 2is3.0).//floor division: drops the fraction, rounds down toward negative infinity (-7 // 3is-3).%remainder/modulo;n % 2 == 0tests even.**power;9 ** 0.5is the square root (3.0).- Int-only operands keep int result (except
/); any float makes the result float.
Float pitfalls
- Floats are approximate:
0.1 + 0.2is0.30000000000000004, so0.1 + 0.2 == 0.3isFalse. - Never compare floats with
==; check closeness:abs(a - 0.3) < 1e-9. round(value, places)for display;round(2.5)is2— banker’s rounding (ties go to nearest even).
Strings
- Text in quotes (single or double);
""is empty. len(s)= character count.- Indexing
s[i]starts at0;-1is last. Out-of-range raisesIndexError. - Slicing
s[start:stop]includes start, excludes stop; omit a side for begin/end. - f-strings:
f"{name} is {age}"drops values into text. - Methods:
.upper() .lower() .strip() .replace(a,b) .split(sep);.split()returns a list. "ell" in "hello"tests substring, returns a boolean.- Immutable: can’t change a character in place; operations build a new string.
- Building a string by repeated
+in a loop is O(n^2); collect pieces and"".join(parts)is O(n).
Booleans
- Exactly
TrueorFalse(capitalized). - Comparisons return booleans:
== != < > <= >=.=assigns,==compares. - String comparison is alphabetical by character code; case matters.
- Logic:
and(both true),or(at least one),not(flip). - Truthiness: falsy values are
0/0.0,"",[],None; almost everything else is truthy. Soif items:means “non-empty.”
Index map for “hello”
h e l l o
0 1 2 3 4 <- positive
-5 -4 -3 -2 -1 <- negative