Tokens: the smallest pieces of a program
A token is the smallest meaningful piece of a Python program. There are five kinds.
- Keywords: words with a fixed meaning, like
if,for,def,True,None. You cannot use them as names. - Identifiers: names you make, like
totalormarks_1. They start with a letter or underscore, never a digit, and have no spaces. - Literals: fixed values, like
25,3.5,'hello',True,None. - Operators: symbols that do work, like
+,==,and. - Punctuators: marks like
( ) [ ] { } : , #.
Data types and mutable vs immutable
Every value has a type. Use type(x) to see it.
- Numbers:
int(whole numbers),float(decimals),complex(like2+3j),bool(True/False). - Sequences:
str,list,tuple. - Mapping:
dict(key : value pairs). None: means "no value".
Mutable and immutable
Mutable means "can be changed in the same place in memory". Immutable means "cannot be changed; a new value is made instead".
- Mutable: list, dict, set.
- Immutable: int, float, bool, str, tuple.
You can check with id(x). After L.append(4), id(L) stays the same. After n = n + 1, id(n) changes.
Operators and precedence
- Arithmetic:
+ - * / // % **./always gives a float (7/2 = 3.5).//is floor division (7//2 = 3,-7//2 = -4).%gives the remainder. - Relational:
== != < > <= >=give True or False. - Logical:
not,and,or. - Assignment:
= += -= *=and so on. - Identity:
is,is not(same object?). Membership:in,not in.
Order (highest first)
() → ** → unary - → * / // % → + - → comparisons → not → and → or. Note: ** works right to left, so 2**3**2 = 2**9 = 512.
Flow of control: if, for, while, break, continue
if-elif-else checks conditions from the top. The first True one runs; the rest are skipped.
for goes through each item: for i in range(1, 6): gives 1 to 5. range(start, stop, step) never includes stop.
while repeats as long as the condition is True. Change the variable inside, or the loop never ends.
break leaves the loop at once. continue skips the rest of this turn and goes to the next. A loop's else part runs only if the loop ended without break.
Strings
A string is a row of characters. Index 0 is the first; -1 is the last.
Slicing: s[start:stop:step]. For s = 'PYTHON': s[1:4] = 'YTH', s[::-1] = 'NOHTYP', s[-3:] = 'HON'.
Strings are immutable: s[0] = 'J' gives an error. Useful methods: len(), upper(), lower(), title(), count(), find(), replace(), split(), join(), strip(), isdigit(), isalpha().
Lists, tuples and dictionaries
List (mutable)
L = [10, 20, 30]. Methods: append(x) adds one item at the end, extend(seq) adds many, insert(i, x), pop(i) removes by index and returns it, remove(x) removes by value, sort(), reverse(), index(x), count(x).
Tuple (immutable)
T = (10, 20, 30). A one-item tuple needs a comma: (5,). Only count() and index(). Good for data that must not change.
Dictionary (mutable)
D = {'Asha': 92, 'Ravi': 75}. Keys must be unique and immutable. D['Zoya'] = 81 adds or updates. Methods: keys(), values(), items(), get(k), update(), pop(k), del D[k].
Try it: predict before you run
Open Python (IDLE or any online editor). For each line, write your guess first, then run it: print(7//2, -7//2, 7%3), print('PYTHON'[1:4]), L=[1,2]; M=L; M.append(3); print(L), print(2**3**2). Every wrong guess shows you a rule to revise. Then use the free-play step in the 3D to test mutable and immutable types.
Key formulas and definitions
- Mutable: list, dict, set · Immutable: int, float, bool, str, tuple
- Precedence: () > ** > unary - > * / // % > + - > comparisons > not > and > or
- s[start:stop:step]: stop is not included
- range(start, stop, step): stop is not included
Worked examples
1. Find the output: print(17 // 5, 17 % 5, 17 / 5)
17 // 5 = 3 (whole part). 17 % 5 = 2 (remainder). 17 / 5 = 3.4 (always float). Output: 3 2 3.4
2. Evaluate: 10 + 4 * 3 ** 2 // 6
** first: 3 ** 2 = 9. Then left to right among * and //: 4 * 9 = 36, 36 // 6 = 6. Then + : 10 + 6 = 16.
3. s = 'COMPUTER'. Find s[2:6], s[-3:], s[::2].
Indexes: C0 O1 M2 P3 U4 T5 E6 R7. s[2:6] = 'MPUT'. s[-3:] = 'TER'. s[::2] takes 0,2,4,6 = 'CMUE'.
4. L = [5, 2, 8]; M = L; M.append(1); print(L). What is printed and why?
M = L does not copy; both names point to the same list. Appending through M changes that one list. Output: [5, 2, 8, 1].
5. Write a program to count vowels in a string entered by the user.
s = input('Enter text: ') count = 0 for ch in s.lower(): if ch in 'aeiou': count += 1 print('Vowels:', count)
6. D = {'a': 1, 'b': 2}. After D['a'] = 10 and D['c'] = 3, what is D? What does D.get('z', 0) return?
An existing key is updated; a new key is added. D = {'a': 10, 'b': 2, 'c': 3}. D.get('z', 0) returns 0 because 'z' is not a key (no error).
Common mistakes
- Thinking t = (5) is a tuple. It is just the int 5; write (5,).
- Thinking M = L makes a copy. Use L.copy() or L[:] for a real copy.
- Forgetting that the stop value in range() and slicing is not included.
- Using = instead of == in a condition, or trying s[0] = 'X' on a string.