Free preview · Lesson 1
Data Types, Operators and Strings
Built-in types
- int, float, bool, str, NoneType
- Collections: list (mutable), tuple (immutable), dict, set
- Check a type with type(x); compare types with isinstance(x, int).
Operators that trip people up
- / always returns a float: 10 / 2 gives 5.0.
- // is floor division (rounds towards minus infinity): 7 // 2 is 3 but -7 // 2 is -4.
- % gives the remainder with the sign of the divisor: 7 % 2 is 1.
- is power: 2 10 is 1024.
Truthiness
Empty values are False: 0, 0.0, "", [], {}, set(), None. Everything else is True – including the string "0".
print(bool(""), bool("0"), bool([])) # False True FalseStrings
Strings are immutable sequences. Slicing is s[start:stop:step], stop excluded.
s = "placement"
print(s[2:6]) # acem
print(s[::-1]) # tnemecalp (reversed)
print(s.upper(), s.count("e"), len(s)) # PLACEMENT 2 9
name = "Anu"
print(f"Hello, {name}!") # f-strings for formattingMutability matters
Assigning a list to a new name does not copy it – both names point to the same object. Use list.copy() or slicing a[:] to copy.
a = [1, 2, 3]
b = a
b.append(4)
print(a) # [1, 2, 3, 4]