Class 12 Computer Science Chapter 01 ยท 22 min read

๐Ÿ Python Revision Tour I

Unit 1 ยท Ch 1 Nov 02, 2026
Chapter Quiz Share

Welcome to the Class 12 Python Revision Tour! This unit recaps the fundamentals of Python you learned in Class 11.

๐Ÿ’ก How to use these notes

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.

๐Ÿ“‹ 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.

๐Ÿ”‘

Keywords

Reserved words โ€” cannot be used as variable names

ifwhiledefimport
๐Ÿท

Identifiers

Names you give to variables, functions, classes

my_varcalc_sum
๐Ÿ“ฆ

Literals

Fixed/constant values directly written in code

42"Hello"3.14True
โž•

Operators

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

โš  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 and age are two different names โ€”
๐Ÿง  Memory Trick

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).

๐Ÿ“‹ 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

# 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
โš  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

# 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'>
๐Ÿ“‹ Board Exam Tip

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
๐Ÿ“‹ Board Exam Tip

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)
โš  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'>
๐Ÿ’ก 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

# 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!
๐Ÿ“‹ 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
๐Ÿ“‹ Board Exam Tip โ€” Operator Precedence (PEMDAS)

Precedence order (high โ†’ low): ( ) Parentheses โ†’ ** Exponent โ†’ *, /, //, % โ†’ +, - Example: 2 + 3 * 4 ** 2 = 2 + 3 * 16 = 2 + 48 = 50

โš  / vs // โ€” Know the Difference!

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:

Sequential Flow Conditional Flow Iterative Flow
Statements execute one by one | Decision-based branching | Repeating a block (loops)
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
๐Ÿ“‹ 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.

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:

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)
๐Ÿ“‹ 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:

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!")
โš  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

# 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
๐Ÿ“‹ Board Exam Tip

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:
# * 
# * * 
# * * * 
# * * * * 
# * * * * * 
๐Ÿ“‹ Board Exam Tip

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).

๐Ÿ”‘ Rule

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

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)
Take the Chapter 01 Quiz Custom Quiz
Solved Board Questions

Practice real board exam questions for this chapter.

View Solved Board Questions
Learning Support

Need Help With This Chapter?

Save key topics for exam revision, ask questions to teachers, or submit content corrections.

Verified Doubts & Teacher Answers

Chapter 01 Quiz