Python Revision Tour
Chapter 1 — Class XII Quick Notes
1.2 Tokens in Python
Think of tokens as the 'words' of Python — the smallest meaningful units.
5 types: Keywords | Identifiers | Literals | Operators | Punctuators
1.2.1 Keywords
Reserved words — can't be used as variable names. Python is case-sensitive, so True ≠ true.
Category Examples
Boolean / None True, False, None
Logic and, or, not, is, in
Flow if, elif, else, for, while, break, continue, pass, return
Scope / Module global, nonlocal, import, from, as, del, with
OOP class, def, lambda, yield
Error Handling try, except, finally, raise, assert
1.2.2 Identifiers (Names)
Names given to variables, functions, classes, etc.
Rules (analogy = naming a file):
• Only letters (A–Z, a–z), digits (0–9), underscore (_)
• Cannot start with a digit
• No spaces, no special chars (-, ., @, etc.)
• Cannot be a keyword
📌 Python IS case-sensitive: myVar ≠ MyVar ≠ MYVAR
✅ Valid ❌ Invalid Why Invalid
Myfile, _DS, FILE13 DATA-REC hyphen not allowed
Z2T0Z9, _HJI3_JK 29CLCT starts with digit
DATE9_7_77 break reserved keyword
[Link] dot not allowed
1.2.3 Literals / Values
Fixed/constant data items directly written in code.
(i) String Literals
• Sequence of chars in single/double/triple quotes
• Single-line: closing quote on same line
•
Key escape sequences:
Seq Meaning Seq Meaning
\n New line \t Tab
\\ Backslash \' Single quote
\" Double quote \r Carriage return
\a Bell (BEL) \b Backspace
(ii) Numeric Literals
Type Form Example
int (signed) Decimal (1-9...), Octal (0o...), Hex (0x...) 1234, 0o35, 0x73
float Decimal or Exponent form -13.0, .75, 0.17E5
complex a + bJ (a=real, b=imaginary) 3 + 4J
📌 Octal digits: 0–7 only (8 & 9 are invalid). Hex digits: 0–9, A–F.
(iii) Boolean Literals
Only two values: True (=1) and False (=0). Boolean is a subtype of int.
(iv) Special Literal — None
None = 'no value / absence of value'. Like null in other languages.
1.2.4 Operators
Category Operators
Arithmetic + − * / % ** //
Relational > < >= <= == !=
Logical and or not
Assignment = /= += −= *= %= **= //=
Membership in not in
Identity is is not
Bitwise & ^ | << >>
1.2.5 Punctuators
Symbols that organize code structure:
' " # \ ( ) [ ] { } @ , : . ` =
1.3 Barebones of a Python Program
Component What it is Example
Expression Any combo of ops + literals → produces a value a + 3, b - 10
Statement Programming instruction a = 15
Comment Human notes, ignored by Python. # = single- # This is a comment
line; ''' = multi-line
Function Named reusable code block def SeeYou():
Block/Suite Group of statements at same indent level if/else body
(after :)
📌 Indentation defines blocks in Python — no curly braces like C/C++!
1.4 Variables & Assignments
Variable = labelled storage location. In Python, variable is just a label (reference) pointing to an object.
1.4.1 Dynamic Typing
Python variables don't have a fixed type — the label can point to any type of object.
X = 10 # X → int object
X = 'Hello' # X now → str object (no error!)
Dynamic Typing Static Typing
Type can change anytime Type fixed at declaration
Python, JS, Ruby C, C++, Java
No type declaration needed Must declare type: int x = 5
1.4.2 Multiple Assignments
• → Same value → multiple vars:
a = b = c = 10
• → Different values → multiple vars (order-wise):
x, y, z = 10, 20, 30
• → Swap (Pythonic!):
x, y = y, x
1.5 Simple Input & Output
input() Function
Always returns a string! Use int() or float() to convert.
name = input('What is your name? ')
age = int(input('Your age? '))
marks = float(input('Marks? '))
📌 Combining int/float with input is the standard way to read numbers.
print() Function
Syntax: print(*objects, sep=' ', end='\n')
• Auto-converts items to string before printing
• Default sep = space between items
• Default end = newline (\n)
Code Output Why
print("My","name","is","Amit.") My name is Amit. default sep = space
print("My","name",sep="...") My...name custom sep
print("Hi.", end="$") print("Bye") Hi.$Bye custom end, no newline
1.6 Data Types
Think of data types as 'categories' that tell Python what kind of data is stored and what ops are valid.
Category Types Key Notes
Numbers int, float, complex, bool bool is subtype of int (True=1, False=0)
Sequence str, list, tuple Indexed from 0; negative index counts from end
(-1=last)
Mapping dict Key-value pairs; keys must be unique
Set set Unordered, no duplicates, mutable
None NoneType Special — represents 'no value'
Number Details
• int: unlimited range (limited only by RAM)
• float: 15-digit precision (machine-level double precision)
• complex: stored as A + Bj; use [Link], [Link] to extract parts
Strings
• Pure Unicode sequences in Python 3.x
• Each char has an index: 0, 1, 2 ... (forward) or -1, -2 ... (backward)
Lists vs Tuples vs Sets vs Dicts
Type Syntax Mutable? Ordered? Duplicates?
list [1, 2, 'a'] Yes Yes Yes
tuple (1, 2, 'a') No Yes Yes
set {1, 2, 3} Yes No No
dict {'a':1, 'b':2} Yes No (3.7+ Keys: No, Values: Yes
yes)
1.7 Mutable & Immutable Types
Immutable (Can't change in place) Mutable (Can change in place)
int, float, complex, bool, str, tuple list, dict, set
Variable label moves to a new memory address Value changes at same memory address
when value changes
p = 5; q = p → both point to same object at addr X Chk = [2,4,6]; Chk[1] = 40 → Chk is now [2,40,6]
📌 Analogy: Immutable = sticky note (write new one to change); Mutable = whiteboard (erase &
rewrite in place).
1.8 Expressions
Type Description Example
Arithmetic Numbers + arithmetic ops 2 + 5**3, -8*6/5
Relational Comparison → returns True/False x > y, a <= N <= b
Logical Boolean ops a and b, not c or d
String + (concat) or * (replicate) "and"+"then" → "andthen"
1.8.1 Operator Precedence (High → Low)
Precedence Operator(s) Description
1 (Highest) () Parentheses
2 ** Exponentiation
3 ~x, +x, -x Bitwise NOT, Unary +/−
4 * / // % Multiply, Divide, Floor div, Mod
5 +− Add, Subtract
6 &^| Bitwise AND, XOR, OR
7 < <= > >= == != is is not in not in Comparison / Identity / Membership
8 not Boolean NOT
9 and Boolean AND
10 (Lowest) or Boolean OR
1.8.2 Type Promotion in Mixed Expressions
• int op int → int (except / which always gives float)
• int op float → float
• any op complex → complex
6 / 3 → 2.0 (float!)
6 // 3 → 2 (int)
6.0 % 3 → 0.0 (float)
1.8.3 Logical Expression Evaluation
• Arithmetic evaluated first, then logical
• Precedence of logical: not > and > or
• Short-circuit: in OR, 2nd arg evaluated only if 1st is False; in AND, only if 1st is True
25/5 or 2.0 + 20/10 → evaluates as: 5 or 4.0 → result 5
1.8.4 Type Casting (Explicit Conversion)
Forcing an expression into a specific type using type-name as a function.
int(b) # converts b to int
float(x) # converts x to float
str(n) # converts n to string
bool(0) # → False; bool(5) → True
📌 Analogy: Type casting = pouring water (data) into a differently shaped mould (type).
1.8.5 Math Library Functions
Import first: import math then use math.<function>
Function Usage Returns
ceil [Link](1.03) 2 (smallest int ≥ num)
floor [Link](1.03) 1 (largest int ≤ num)
sqrt [Link](81.0) 9.0
fabs [Link](-5) 5.0 (absolute value)
pow [Link](4.0, 2.0) 16.0 (= base^exp)
log [Link](1024, 2) log of 1024 base 2
log10 math.log10(100) 2.0
exp [Link](2.0) e² value
factorial [Link](4) 24
gcd [Link](8, 6) 2
sin/cos/tan [Link](val) val must be in radians
degrees [Link](3.14) 179.91 (rad → deg)
radians [Link](180) 3.14 (deg → rad)
—— End of Chapter 1 Notes ——