Welcome to the Class 12 Python Revision Tour! This unit recaps the fundamentals of Python you learned in Class 11.
Read each section once, then run the code examples yourself. Pay extra attention to the ๐ Board Exam Tips.
1.1 Introduction
Python is one of the most popular, beginner-friendly programming languages in the world. In Class 12, Chapter 1 is a revision tour โ not new content, but a quick, structured recap of everything from Class 11 before you move into advanced topics like functions, files, and databases.
Python was created by Guido van Rossum and first released in 1991. It is an interpreted, high-level, general-purpose language known for its clean, readable syntax.
- ๐ง Type: Interpreted
- ๐ฅ Paradigm: Multi-paradigm (OOP + Procedural)
- ๐ฆ Version: Python 3.x
- ๐ค Case-Sensitive: Yes
1.2 Tokens in Python
A token is the smallest individual unit of a Python program. Think of tokens as the "atoms" of your code โ every single element you write belongs to one of five token categories.
"What are tokens? Name the types of tokens in Python." is a direct 2-mark question. Always list all five: Keywords, Identifiers, Literals, Operators, Punctuators.
Keywords
Reserved words โ cannot be used as variable names
ifwhiledefimportIdentifiers
Names you give to variables, functions, classes
my_varcalc_sumLiterals
Fixed/constant values directly written in code
42"Hello"3.14TrueOperators
Symbols that perform operations on values
+-*/**%Punctuators
Symbols that organise the code structure
( )[ ]{ }:#1.2.1 Keywords
Python 3 has 35 reserved keywords. They have fixed meanings and cannot be used as identifiers.
False, None, True, and, as, assert, async, await, break, class, continue, def, del, elif, else, except, finally, for, from, global, if, import, in, is, lambda, nonlocal, not, or, pass, raise, return, try, while, with, yield
Keywords are case-sensitive. True is a keyword but true is NOT โ it's a valid variable name!
1.2.2 Identifiers (Names)
An identifier is a name given to a variable, function, class, module, or any other object.
| Rule | Valid โ | Invalid โ |
|---|---|---|
| Letters, digits, underscore only | age_1 |
age-1 |
Must start with letter or _ |
_name |
1name |
| Cannot be a keyword | myif |
if |
| No spaces allowed | my_var |
my var |
| Case-sensitive | Age and age are two different names |
โ |
Remember valid identifier characters as L-D-U: Letters, Digits, Underscore. And it must START with L or U โ never a digit!
1.2.3 Literals / Values
| Type | Examples | Notes |
|---|---|---|
| Integer Literal | 42, -7, 0 |
Whole numbers, no decimal |
| Float Literal | 3.14, -0.5 |
Numbers with decimal point |
| String Literal | "Hello", 'Python' |
Text in quotes |
| Boolean Literal | True, False |
Capitalised โ exact spelling! |
| None Literal | None |
Represents absence of value |
1.2.4 Operators
Operators are special symbols that perform computations. Python has arithmetic (+ - * / // % **), relational (== != > < >= <=), logical (and or not), bitwise, membership, and identity operators.
1.2.5 Punctuators
Punctuators give structure to code. Key punctuators in Python:
(), [], {}, :, ,, ., @, =, ;, # (comment), \ (continuation).
The colon : is a punctuator used to start blocks (after if, for, def, etc.). Missing the colon is a very common SyntaxError in board practicals.
1.3 Barebones of a Python Program
Every Python program, no matter how complex, is made of the same basic building blocks.
Code Example: hello_world.py
# hello_world.py
# โ Comment โ ignored by Python, explains what code does
# โก Import statement โ loads extra tools (modules)
import math
# โข Variable declaration โ stores data
student_name = "Arjun"
marks = 95
# โฃ Expression / Statement โ performs an action
percentage = (marks / 100) * 100
# โค Output โ shows result to user
print(f"Hello, {student_name}! Your score: {marks}")
| Element | What it does | Example |
|---|---|---|
| Comment | Non-executing note for humans | # This is a comment |
| Statement | One instruction for Python to execute | x = 5 |
| Expression | Combination of values/operators that produces a result | 5 + 3 * 2 |
| Block | Group of statements with same indentation | Body of if, for, etc. |
| Indentation | 4 spaces โ defines code blocks (no braces!) | Space before statements in a loop |
Python uses indentation (4 spaces) instead of { } braces to define blocks. Mixing tabs and spaces, or wrong indentation depth, will cause an IndentationError at runtime. Always use consistent 4-space indentation.
1.4 Variables and Assignments
A variable is a named location in memory that holds a value. In Python, you create a variable simply by assigning a value to a name using the = operator.
1.4.1 Dynamic Typing
Python is dynamically typed โ a variable's type is determined at runtime, not at declaration time. The same variable can hold values of different types during its lifetime.
Code Example: dynamic_typing.py
# dynamic_typing.py
x = 10 # x is int
print(type(x)) # <class 'int'>
x = "Hello" # Now x is str (same variable!)
print(type(x)) # <class 'str'>
x = 3.14 # Now x is float
print(type(x)) # <class 'float'>
A typical question: "What is dynamic typing?" โ Answer: In Python, you do not need to declare the data type of a variable. The type is automatically determined based on the value assigned, and it can change during program execution.
1.4.2 Multiple Assignments
Code Example: assignments.py
# assignments.py
# โ Same value to multiple variables
a = b = c = 100
print(a, b, c) # 100 100 100
# โก Different values in one line (tuple unpacking)
x, y, z = 10, 20, 30
print(x, y, z) # 10 20 30
# โข Swapping โ NO temporary variable needed!
a, b = 5, 8
a, b = b, a # Elegant Python swap!
print(a, b) # 8 5
Swap in Python using a, b = b, a. It can be asked as a 1-mark question.
1.5 Simple Input and Output
- ๐ฅ input() function:
input("prompt")โ Returns a string ALWAYS.- Use
int(input(...))for numbers. - Use
float(input(...))for decimals.
- ๐ค print() function:
sep=" "โ separator between items.end="\n"โ what to print at end.- f-strings:
f"Hello {name}".
Code Example: input_output.py
# input_output.py
# Taking input
name = input("Enter your name: ")
age = int(input("Enter your age: "))
# Regular print
print("Hello,", name) # Hello, Arjun
# f-string (formatted string โ preferred!)
print(f"You are {age} years old.")
# Controlling separator and end
print("A", "B", "C", sep="-") # A-B-C
print("Line 1", end=" ")
print("Line 2") # Line 1 Line 2 (same line)
input() always returns a string, even if the user types 25. Forgetting to convert with int() or float() causes a TypeError when doing arithmetic.
1.6 Data Types
Python is dynamically typed but every value has a type. Python handles all of these automatically โ no need to declare types like in C or Java.
| Category | Data Type | Example | type() returns |
|---|---|---|---|
| Numeric | Integer | 42, -7 |
<class 'int'> |
| Numeric | Float | 3.14, -0.5 |
<class 'float'> |
| Numeric | Complex | 3+4j |
<class 'complex'> |
| Text | String (str) | "Hello", 'Python' |
<class 'str'> |
| Boolean | bool | True, False |
<class 'bool'> |
| Sequence | List | [1, 2, 3] |
<class 'list'> |
| Sequence | Tuple | (1, 2, 3) |
<class 'tuple'> |
| Mapping | Dictionary | {'a': 1} |
<class 'dict'> |
| Set | Set | {1, 2, 3} |
<class 'set'> |
| None | NoneType | None |
<class 'NoneType'> |
Use type(variable) to check the type of any variable. Use isinstance(x, int) to check if a variable is of a specific type โ preferred in real-world code.
1.7 Mutable and Immutable Types
This is one of the most important conceptual distinctions in Python โ and a frequent exam question.
- ๐ Immutable Types: Once created, the value cannot be changed in place. A new object is created on modification.
- Examples:
int- whole numbers,float- decimal numbers,str- text strings,tuple- fixed sequence,bool- True / False.
- Examples:
- ๐ Mutable Types: Values can be changed in place after creation without creating a new object.
- Examples:
list- mutable sequence,dict- key-value pairs,set- unique collection.
- Examples:
Code Example: mutable_demo.py
# mutable_demo.py
# IMMUTABLE โ string cannot be changed in place
s = "Hello"
# s[0] = "J" โ TypeError: 'str' object does not support item assignment
# MUTABLE โ list CAN be changed in place
my_list = [1, 2, 3]
my_list[0] = 100 # โ
Allowed!
print(my_list) # [100, 2, 3]
# IMMUTABLE โ tuple CANNOT be changed
my_tuple = (1, 2, 3)
# my_tuple[0] = 100 โ TypeError!
"Differentiate between mutable and immutable data types with examples" โ This is a 3-mark question. Always give at least 2 examples of each and explain what happens when you try to modify an immutable type.
1.8 Expressions
An expression is a combination of values, variables, and operators that Python evaluates to produce a result. Expressions always produce a value.
1.8.1 Evaluating Arithmetic Operations
| Operator | Name | Example | Result |
|---|---|---|---|
+ |
Addition | 10 + 3 |
13 |
- |
Subtraction | 10 - 3 |
7 |
* |
Multiplication | 10 * 3 |
30 |
/ |
Division (float) | 10 / 3 |
3.3333... |
// |
Floor Division | 10 // 3 |
3 |
% |
Modulus (remainder) | 10 % 3 |
1 |
** |
Exponentiation | 2 ** 10 |
1024 |
Precedence order (high โ low):
( ) Parentheses โ ** Exponent โ *, /, //, % โ +, -
Example: 2 + 3 * 4 ** 2 = 2 + 3 * 16 = 2 + 48 = 50
7 / 2 โ 3.5 (always float) | 7 // 2 โ 3 (always integer, rounded down)
-7 // 2 โ -4 (not -3) โ floor division rounds towards negative infinity!
1.8.2 Evaluating Relational Expressions
Relational (comparison) operators always return True or False.
Code Example: relational.py
# relational.py
x, y = 10, 20
print(x == y) # False โ equal to
print(x != y) # True โ not equal
print(x < y) # True โ less than
print(x >= y) # False โ greater than or equal
print(5 < 10 < 15) # True โ Python allows chaining!
1.8.3 Evaluating Logical Expressions
| Operator | Returns True when... | Example |
|---|---|---|
and |
BOTH operands are True | True and False โ False |
or |
AT LEAST ONE operand is True | True or False โ True |
not |
Operand is False (reverses) | not True โ False |
Code Example: logical.py
# logical.py
age = 17
has_id = True
# Both conditions must be True
can_vote = (age >= 18) and has_id
print(can_vote) # False
# At least one condition must be True
is_weekend = True
has_homework = False
can_play = is_weekend or has_homework
print(can_play) # True
# Reverse the boolean value
print(not has_id) # False
1.8.4 Type Casting
Converting one data type to another explicitly.
| Function | What it does | Example |
|---|---|---|
int() |
Convert to integer | int("18") โ 18 |
float() |
Convert to float | float(5) โ 5.0 |
str() |
Convert to string | str(95) โ "95" |
list() |
Convert to list | list((1, 2, 3)) โ [1, 2, 3] |
tuple() |
Convert to tuple | tuple([1, 2, 3]) โ (1, 2, 3) |
Code Example: type_casting.py
# String to Integer
age_str = "18"
age = int(age_str)
print(age) # 18
# Float to Integer (truncates decimal)
pi = 3.14
pi_int = int(pi)
print(pi_int) # 3
# Integer to String
marks = 95
marks_str = str(marks)
print(marks_str) # "95"
1.8.5 Math Library
The math module provides mathematical functions.
| Function | What it does | Example |
|---|---|---|
math.sqrt(x) |
Square root | math.sqrt(16) โ 4.0 |
math.pow(x, y) |
Power ($x^y$) | math.pow(2, 3) โ 8.0 |
math.ceil(x) |
Ceiling (rounds up) | math.ceil(3.2) โ 4 |
math.floor(x) |
Floor (rounds down) | math.floor(3.8) โ 3 |
math.factorial(x) |
Factorial | math.factorial(5) โ 120 |
Code Example: math_functions.py
import math
print(math.sqrt(16)) # 4.0
print(math.pow(2, 3)) # 8.0
print(math.ceil(3.2)) # 4
print(math.floor(3.8)) # 3
print(math.factorial(5)) # 120
print(math.pi) # 3.14159...
1.9 Statement Flow Control
In Python, execution statements can flow in three structured paths:
| Flow Type | How It Works | Python Constructs |
|---|---|---|
| Sequential | Statements run top to bottom, one after another | Normal statements |
| Conditional | A block runs only if a condition is True | if if-else if-elif-else |
| Iterative | A block repeats while a condition holds | for while |
1.10 Conditional Statements
if Statement
Executes code only if condition is True.
if-else Statement
Executes one block if condition is True, another if False.
if-elif-else Statement
Checks multiple conditions in sequence.
Code Example: conditionals.py
# Simple if
age = 18
if age >= 18:
print("You can vote")
# if-else
marks = 65
if marks >= 40:
print("Pass")
else:
print("Fail")
# if-elif-else
marks = 85
if marks >= 90:
grade = 'A+'
elif marks >= 80:
grade = 'A'
elif marks >= 70:
grade = 'B'
elif marks >= 60:
grade = 'C'
else:
grade = 'D'
print(f"Grade: {grade}") # Grade: A
Ensure proper 4-space indentation for the code blocks under if, elif, and else. Wrong indentation will raise an IndentationError.
Nested if Statements
An if statement inside another if statement. Each level must be properly indented.
num = int(input("Enter a number: "))
if num != 0:
if num > 0:
print("Positive number")
else:
print("Negative number")
else:
print("Zero")
1.11 Looping Statements
Loops let you repeat a block of code multiple times without rewriting it. Python has two loop types.
for Loop
The for loop iterates over a sequence (list, tuple, string, range) and runs the block once for each item.
Syntax:
for <variable> in <sequence>:
<body>Code Example: for_loops.py
# for loop with range
for i in range(1, 6):
print(i) # Prints 1 to 5
# for loop with list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
range(stop) โ 0 to stop-1 | range(start, stop) โ start to stop-1 | range(start, stop, step) โ with step size
Stop value is NEVER included. range(1, 6) gives 1, 2, 3, 4, 5 โ not 6!
while Loop
The while loop repeats as long as a condition remains True. Use when you don't know in advance how many times to loop.
Syntax:
while <condition>:
<body>Code Example: while_loops.py
# while loop
count = 1
while count <= 5:
print(count)
count += 1
# while loop with user input
password = ""
while password != "python123":
password = input("Enter password: ")
print("Access granted!")
If the loop condition never becomes False, the loop runs forever โ this is an infinite loop. Always make sure something inside the loop changes the condition. Press Ctrl+C to stop an infinite loop.
1.12 Jump Statements
Jump statements alter the normal flow of a loop. Python has three: break, continue, and pass.
- ๐ break
- Immediately exits the loop
- Control goes to next statement after loop
- Works in both for and while
- โญ continue
- Skips rest of current iteration
- Control goes to next iteration
- Works in both for and while
Code Example: jump_statements.py
# break - Find first multiple of 7
for i in range(1, 100):
if i % 7 == 0:
print(f"First multiple of 7: {i}")
break # Exit loop
# continue - Print only odd numbers
for i in range(1, 11):
if i % 2 == 0: # If even
continue # Skip this iteration
print(i) # Only prints odd numbers
# Output: 1 3 5 7 9
A typical question: "What is the difference between break and continue?" break โ terminates the entire loop. continue โ terminates only the current iteration and moves to the next. Both work inside any loop body.
1.13 More on Loops
1.13.1 Nested Loops
A loop inside another loop. The inner loop completes all its iterations for every single iteration of the outer loop.
Code Example: nested_loops.py
# Multiplication table
for i in range(1, 4):
for j in range(1, 4):
print(f"{i} x {j} = {i*j}")
print() # Blank line
# Pattern printing
for i in range(1, 6):
for j in range(i):
print("*", end=" ")
print() # New line
# Output:
# *
# * *
# * * *
# * * * *
# * * * * *
Loop-else is a typical topic for 2โ3 mark questions. The classic use case is prime number checking. Remember: else block skipped if break executed; runs if loop completes normally.
1.13.2 Loop else Statement
Python allows an else clause on loops โ a feature unique to Python! The else block executes only when the loop finishes normally (i.e., no break occurred).
If break executes โ else is skipped. If loop finishes naturally โ else runs.
Code Example: loop_else.py
# Check if number is prime
num = 17
for i in range(2, num):
if num % i == 0:
print(f"{num} is not prime")
break
else:
print(f"{num} is prime") # Executes if no break occurred
Tokens: the 5 types
- Keywords โ reserved words (
if,for,True,None); case-sensitive, can never be used as names - Identifiers โ names you choose: letters, digits and
_only, cannot start with a digit, cannot be a keyword, case-sensitive - Literals โ fixed values:
42,3.14,"Hi",True,None - Operators โ arithmetic
+ - * / // % **, relational== != < > <= >=, logicaland or not - Punctuators โ
( ),[ ],{ },:,,,.,#
Variables, Input and Output
- Dynamic typing โ the type comes from the value at run time and can change:
x = 10thenx = "Hi" a = b = c = 0โ same value |x, y = 10, 20โ unpacking |a, b = b, aโ swapinput()always returns a string โ useint(input())orfloat(input())for numbersprint("A", "B", sep="-", end=" ")โsepgoes between items,endreplaces the newline
Data Types and Mutability
| Immutable (cannot change in place) | Mutable (can change in place) |
|---|---|
int, float, bool, str, tuple |
list, dict, set |
Changing an immutable object in place gives a TypeError, e.g. s = "Hello" then s[0] = "J".
Expressions: results to remember
| Expression | Result | Why |
|---|---|---|
7 / 2 |
3.5 |
/ always gives a float |
7 // 2 |
3 |
floor division |
-7 // 2 |
-4 |
rounds down, towards minus infinity |
7 % 2 |
1 |
remainder |
2 + 3 * 4 ** 2 |
50 |
** first, then *, then + |
2 ** 3 ** 2 |
512 |
** works right to left: 2 ** 9 |
5 < 10 < 15 |
True |
comparisons can be chained |
int(3.9) |
3 |
int() cuts off the decimal part |
math.sqrt(16) |
4.0 |
math functions like sqrt and pow return a float |
Precedence (high to low): () โ ** โ * / // % โ + - โ relational โ not โ and โ or
Flow of Control
- Sequential โ one after another | Conditional โ
if,if-else,if-elif-else| Iterative โfor,while - A block starts after a colon
:and is marked by the same indentation (4 spaces): missing:โSyntaxError, wrong indent โIndentationError
Loops and Jump Statements
range(5)โ 0 1 2 3 4 |range(2, 6)โ 2 3 4 5 |range(10, 0, -3)โ 10 7 4 1 (the stop value is never included)forโ goes over a sequence or arange()|whileโ repeats while the condition isTrue(change the condition inside, or it loops forever)breakโ leaves the loop |continueโ skips to the next iteration |passโ does nothing (placeholder)- Loop
elseโ runs only when the loop ends without abreak - Nested loop โ the inner loop runs completely for every turn of the outer loop
Quick check: predict the output
for i in range(1, 10, 3):
if i == 7:
break
print(i, end=" ")
else:
print("done")
Output:
1 4
i takes 1, 4, 7. At 7 the loop hits break, so the else block is skipped and "done" is never printed.
Practice Problems
Try these problems to solidify your understanding. These cover all topics in this chapter and are similar to CBSE board exam questions.
- Variables & Input: Write a program to input the radius of a circle and display its area and circumference.
- Conditionals: Write a program to input three numbers and print the largest of the three.
- for Loop: Print the Fibonacci series up to n terms (input n from user).
- while Loop: Find the factorial of a given number using a while loop.
- break: Input numbers from user repeatedly until a negative number is entered. Print the sum of all positive numbers entered.
- continue: Print all numbers from 1 to 50 that are NOT divisible by 3 or 5.
- Loop else: Write a program to check if a number is prime using the loop-else construct.
- Nested Loops: Print a right-angled triangle pattern of numbers (1 on row 1, 1 2 on row 2, etc.).
- String Operations: Input a string. Count and display the number of vowels and consonants in it.
- Type Casting: Input marks of 5 subjects (as strings). Convert, calculate percentage, and display with grade using if-elif.
Quick Reference
Input/Output:
input()โ Read input as stringprint()โ Display output
Type Conversion:
int(x)โ to integerfloat(x)โ to floatstr(x)โ to stringbool(x)โ to booleanlist(x)โ to listtuple(x)โ to tuple
Common Functions:
type(x)โ Get data typelen(x)โ Get lengthrange(x)โ Generate sequence of numbersabs(x)โ Absolute val
Math Module:
- Import first:
import math math.sqrt(),math.pow(),math.ceil(),math.floor(),math.factorial()
Loop Control:
breakโ Exit loopcontinueโ Skip to next iterationpassโ Do nothing (placeholder)elseโ After loop
Operators:
//โ floor division%โ modulus**โ exponent- and, or, not
- == (equal), != (neq)