Welcome to the Class 12 Python Revision Tour! This unit recaps the fundamentals of Python you learned in Class 11.
> [!TIP]
> **How to use these notes:** Read each section once, then run the code examples yourself. Pay extra attention to **📋 Board Exam Tips** — those are examiner favourites.
---
## 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.
> [!IMPORTANT]
> **Board Exam Tip**
> "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.
::: grid
::: card 🔑 | Keywords | Reserved words — cannot be used as variable names | `if`, `while`, `def`, `import`
::: card 🏷 | Identifiers | Names you give to variables, functions, classes | `my_var`, `calc_sum`
::: card 📦 | Literals | Fixed/constant values directly written in code | `42`, `"Hello"`, `3.14`, `True`
::: card ➕ | Operators | Symbols that perform operations on values | `+`, `-`, `*`, `/`, `**`, `%`
::: card 🔣 | 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`, `break`, `class`, `continue`, `def`, `del`, `elif`, `else`, `except`, `finally`, `for`, `from`, `global`, `if`, `import`, `in`, `is`, `lambda`, `not`, `or`, `pass`, `raise`, `return`, `try`, `while`, `with`, `yield`
> [!WARNING]
> **Common Mistake**
> 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` $\neq$ `age` | — |
> [!NOTE]
> **Memory Trick**
> Remember valid identifier characters as **L-D-U**: **L**etters, **D**igits, **U**nderscore. 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).
> [!IMPORTANT]
> **Board Exam Tip**
> 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
```python
# 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 |
> [!WARNING]
> **IndentationError Alert!**
> 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
```python
# 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'>
```
> [!IMPORTANT]
> **Board Exam Tip**
> The examiner often asks: *"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
```python
# 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
```
> [!IMPORTANT]
> **Board Exam Tip**
> Swap in Python using `a, b = b, a` — frequently asked in practical and theory exams. This is a **1-mark guaranteed topic**.
---
## 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
```python
# 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)
```
> [!WARNING]
> **Classic Trap**
> `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'>` |
> [!TIP]
> **Pro Tip**
> 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.
* **🔓 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.
### Code Example: mutable_demo.py
```python
# 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!
```
> [!IMPORTANT]
> **Board Exam Tip**
> "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` |
> [!IMPORTANT]
> **Board Exam Tip — Operator Precedence (PEMDAS)**
> Precedence order (high → low):
> **( )** Parentheses $\rightarrow$ **\*\*** Exponent $\rightarrow$ **\*, /, //, %** $\rightarrow$ **+, -**
> Example: `2 + 3 * 4 ** 2` = `2 + 3 * 16` = `2 + 48` = `50`
> [!WARNING]
> **/ vs // — Know the Difference!**
> `7 / 2` $\rightarrow$ `3.5` (always float) \| `7 // 2` $\rightarrow$ `3` (always integer, rounded down)
> `-7 // 2` $\rightarrow$ `-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
```python
# 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` $\rightarrow$ `False` |
| `or` | AT LEAST ONE operand is True | `True or False` $\rightarrow$ `True` |
| `not` | Operand is False (reverses) | `not True` $\rightarrow$ `False` |
### Code Example: logical.py
```python
# 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")` $\rightarrow$ `18` |
| `float()` | Convert to float | `float(5)` $\rightarrow$ `5.0` |
| `str()` | Convert to string | `str(95)` $\rightarrow$ `"95"` |
| `list()` | Convert to list | `list((1, 2, 3))` $\rightarrow$ `[1, 2, 3]` |
| `tuple()` | Convert to tuple | `tuple([1, 2, 3])` $\rightarrow$ `(1, 2, 3)` |
### Code Example: type_casting.py
```python
# 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)` $\rightarrow$ `4.0` |
| `math.pow(x, y)` | Power ($x^y$) | `math.pow(2, 3)` $\rightarrow$ `8.0` |
| `math.ceil(x)` | Ceiling (rounds up) | `math.ceil(3.2)` $\rightarrow$ `4` |
| `math.floor(x)` | Floor (rounds down) | `math.floor(3.8)` $\rightarrow$ `3` |
| `math.factorial(x)` | Factorial | `math.factorial(5)` $\rightarrow$ `120` |
### Code Example: math_functions.py
```python
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:
<div class="bg-slate-50/60 dark:bg-slate-900/50 backdrop-blur-sm border border-slate-200/60 dark:border-slate-800/60 rounded-2xl p-6 mb-6 text-center">
<div class="flex flex-wrap justify-center gap-4 mb-4">
<span class="px-4 py-2 rounded-xl border border-emerald-500/30 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 font-bold text-xs md:text-sm tracking-wide">
Sequential Flow
</span>
<span class="px-4 py-2 rounded-xl border border-amber-500/30 bg-amber-500/10 text-amber-600 dark:text-amber-400 font-bold text-xs md:text-sm tracking-wide">
Conditional Flow
</span>
<span class="px-4 py-2 rounded-xl border border-violet-500/30 bg-violet-500/10 text-violet-600 dark:text-violet-400 font-bold text-xs md:text-sm tracking-wide">
Iterative Flow
</span>
</div>
<div class="text-xs text-slate-500 dark:text-slate-400 font-medium flex flex-wrap justify-center items-center gap-2 md:gap-3">
<span>Statements execute one by one</span>
<span class="text-slate-300 dark:text-slate-700">|</span>
<span>Decision-based branching</span>
<span class="text-slate-300 dark:text-slate-700">|</span>
<span>Repeating a block (loops)</span>
</div>
</div>
| Flow Type | How It Works | Python Constructs |
| :--- | :--- | :--- |
| <span class="font-bold text-amber-600 dark:text-amber-400">Sequential</span> | Statements run top to bottom, one after another | Normal statements |
| <span class="font-bold text-amber-600 dark:text-amber-400">Conditional</span> | A block runs only if a condition is True | `if` `if-else` `if-elif-else` |
| <span class="font-bold text-amber-600 dark:text-amber-400">Iterative</span> | 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
```python
# 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
```
> [!IMPORTANT]
> **Board Exam Tip**
> 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.
```python
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.
> [!RULE]
> Syntax:
> ```python
> for <variable> in <sequence>:
> <body>
> ```
### Code Example: for_loops.py
```python
# 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)
```
>[!important]
> **Board Exam Tip — range() function**
> `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.
> [!RULE]
> Syntax:
> ```python
> while <condition>:
> <body>
> ```
### Code Example: while_loops.py
```python
# 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!")
```
> [!WARNING]
> **INFINITE LOOP DANGER!**
> 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
```python
# 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
```
> [!IMPORTANT]
> A very common 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
```python
# 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:
# *
# * *
# * * *
# * * * *
# * * * * *
```
> [!IMPORTANT]
> Loop-else is a favourite 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).
> [!RULE]
> If `break` executes → `else` is skipped. If loop finishes naturally → `else` runs.
### Code Example: loop_else.py
```python
# 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
```
---
## Practice Problems
Try these problems to solidify your understanding. These cover all topics in this chapter and are similar to CBSE board exam questions.
1. ** Variables & Input:** Write a program to input the radius of a circle and display its area and circumference.
2. **Conditionals:** Write a program to input three numbers and print the largest of the three.
3. **for Loop:** Print the Fibonacci series up to n terms (input n from user).
4. **while Loop:** Find the factorial of a given number using a while loop.
5. **break:** Input numbers from user repeatedly until a negative number is entered. Print the sum of all positive numbers entered.
6. **continue:** Print all numbers from 1 to 50 that are NOT divisible by 3 or 5.
7. **Loop else:** Write a program to check if a number is prime using the loop-else construct.
8. **Nested Loops:** Print a right-angled triangle pattern of numbers (1 on row 1, 1 2 on row 2, etc.).
9. **String Operations:** Input a string. Count and display the number of vowels and consonants in it.
10. **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 string
* `print()` — Display output
**Type Conversion:**
* `int(x)` — to integer
* `float(x)`— to float
* `str(x)` — to string
* `bool(x)` — to boolean
* `list(x)` — to list
* `tuple(x)` — to tuple
**Common Functions:**
* `type(x)` — Get data type
* `len(x)` — Get length
* `range(x)` — Generate sequence of numbers
* `abs(x)` — Absolute val
**Math Module:**
* Import first: `import math`
* `math.sqrt()`, `math.pow()`, `math.ceil()`, `math.floor()`, `math.factorial()`
**Loop Control:**
* `break` — Exit loop
* `continue` — Skip to next iteration
* `pass` — Do nothing (placeholder)
* `else` — After loop
**Operators:**
* `//` — floor division
* `%` — modulus
* `**` — exponent
* and, or, not
* == (equal), != (neq)
```
Back to List
Calculating...