C12-U1-CT&P-2-40

 

CBSE CLASS 12 COMPUTER SCIENCE (083)

UNIT 1: COMPUTATIONAL THINKING AND PROGRAMMING – 2

Revision of Python Topics Covered in Class XI

Introduction

Class 12 Computer Science builds upon the Python concepts studied in Class 11.

Before learning advanced Class 12 topics such as:

  • Functions

  • File Handling

  • Data Structures

  • Computer Networks

  • Database Connectivity

students should revise the fundamental Python concepts.

This chapter provides a complete revision of important Class 11 Python topics.


1. INTRODUCTION TO PYTHON

What is Python?

Python is a high-level, general-purpose programming language known for its simple and readable syntax.

Python was created by Guido van Rossum and its first public release was in 1991.

Python is widely used in:

  • Education

  • Web development

  • Artificial Intelligence

  • Machine Learning

  • Data Science

  • Automation

  • Software development

  • Scientific computing

Example

print("Hello World")

Output:

Hello World

2. FEATURES OF PYTHON

Important features of Python include:

1. Simple

Python syntax is easy to learn and understand.

2. Readable

Python programs are generally easy to read.

3. High-Level Language

Programmers do not need to manage most low-level hardware details directly.

4. Interpreted

Python is commonly described as an interpreted language. Python source code is compiled to bytecode and executed by the Python runtime.

5. General Purpose

Python can be used for many different types of applications.

6. Portable

Python programs can generally be run on different operating systems with little or no modification, subject to the required Python environment.

7. Open Source

Python is available under an open-source licence.

8. Dynamically Typed

The type of a variable is determined at runtime.

Example:

x = 10
x = "Python"

The same variable name can refer to values of different types at different times.

9. Object-Oriented

Python supports object-oriented programming.

10. Case-Sensitive

Python distinguishes between uppercase and lowercase letters.

name
Name
NAME

These are different identifiers.


3. PYTHON EXECUTION MODES

Python programs can commonly be executed in two ways:

  1. Interactive Mode

  2. Script Mode


3.1 Interactive Mode

In interactive mode, Python statements are entered one at a time and executed immediately.

Example:

>>> 10 + 20
30

>>> print("Hello")
Hello

Advantages

  • Useful for testing small pieces of code.

  • Immediate output is displayed.

  • Useful for learning and experimentation.


3.2 Script Mode

In script mode, Python code is saved in a file, usually with the .py extension.

Example:

program.py

Program:

a = 10
b = 20

print(a + b)

Output:

30

Difference

Interactive ModeScript Mode
Statements are entered one by oneComplete program is saved in a file
Immediate executionProgram is executed as a file
Good for testingGood for larger programs
Usually temporaryCan be saved and reused

4. PYTHON CHARACTER SET

The Python character set consists of characters that can be used to write Python programs.

It includes:

Letters

A-Z
a-z

Digits

0-9

Whitespace

Examples:

  • Space

  • Tab

  • Newline

Special Symbols

Examples:

+ - * / % = < > ( ) [ ] { } , : . ' " # _

Python also supports Unicode characters in appropriate contexts.


5. PYTHON TOKENS

A token is the smallest individual unit of a Python program that has meaning to the interpreter.

Major categories include:

  1. Keywords

  2. Identifiers

  3. Literals

  4. Operators

  5. Punctuators


6. KEYWORDS

Keywords are reserved words that have special meanings in Python.

Examples:

if
else
elif
for
while
break
continue
def
return
import
from
class
try
except
True
False
None
and
or
not
in
is

Keywords cannot normally be used as variable names.

Incorrect:

if = 10

7. IDENTIFIERS

An identifier is a name used to identify:

  • Variables

  • Functions

  • Classes

  • Objects

  • Other program elements

Examples

student_name = "Amit"
marks = 85
total_marks = 500

Here:

student_name
marks
total_marks

are identifiers.


Rules for Identifiers

  1. Can contain letters.

  2. Can contain digits.

  3. Can contain underscore _.

  4. Cannot begin with a digit.

  5. Cannot contain spaces.

  6. Cannot be a Python keyword.

  7. Python identifiers are case-sensitive.

Valid

name
student1
total_marks
_marks

Invalid

1student
student name
class

8. LITERALS

A literal is a fixed value written directly in a Python program.

Examples:

10
3.14
"Python"
True
None
[1, 2, 3]

Common types include:

  • Integer literals

  • Floating-point literals

  • Complex literals

  • String literals

  • Boolean literals

  • None

  • Collection literals


9. VARIABLES

A variable is a name that refers to a value/object in a Python program.

Example:

age = 17

Here:

age → variable
17  → value

Another example:

name = "Rahul"

Dynamic Typing

Python variables do not need an explicit type declaration.

x = 10
print(type(x))

x = "Hello"
print(type(x))

The type associated with x changes because x now refers to a different object.


10. L-VALUE AND R-VALUE

Consider:

x = 50

The variable x is on the left side of the assignment.

x = 50
↑   ↑
L   R

L-value

The left-hand side identifies the destination or target of an assignment.

R-value

The right-hand side provides the value or expression to be assigned.

Example:

a = b + 10

Here:

a       → assignment target
b + 10  → expression producing the value

11. COMMENTS

Comments are notes written in a program for human readers.

Python ignores comments during normal execution.

Single-Line Comment

Use #.

# This program calculates sum

a = 10
b = 20

print(a + b)

Inline Comment

x = 10       # Store 10 in x

Comments make programs easier to understand and maintain.


12. DATA TYPES

Python provides several built-in data types.

Important Class 11 types include:

Number
Boolean
Sequence
NoneType
Mapping

13. NUMBER DATA TYPES

Python has three important numeric types:

  1. Integer (int)

  2. Floating point (float)

  3. Complex (complex)


13.1 Integer

An integer is a whole number without a decimal part.

Examples:

10
-25
0
1000
x = 25

print(type(x))

Output:

<class 'int'>

13.2 Floating Point

A floating-point number contains a decimal part.

Examples:

3.14
10.5
-2.75
x = 3.14

print(type(x))

13.3 Complex Number

A complex number has a real and an imaginary part.

Python uses j for the imaginary part.

Example:

z = 3 + 4j

print(z)

14. BOOLEAN DATA TYPE

Boolean values are:

True
False

Example:

age = 18

print(age >= 18)

Output:

True

Boolean values are commonly used with conditions.


15. STRING

A string is a sequence of characters.

Strings can be written using:

"Hello"
'Hello'

Example:

name = "Python"

String Indexing

String:   P  Y  T  H  O  N
Index:    0  1  2  3  4  5
Negative: -6 -5 -4 -3 -2 -1

Example:

s = "Python"

print(s[0])
print(s[-1])

Output:

P
n

16. STRING SLICING

Syntax:

string[start:stop:step]

Example:

s = "Python"

print(s[1:4])

Output:

yth

Remember:

The stop index is excluded.


17. STRING OPERATIONS

Concatenation

a = "Hello "
b = "World"

print(a + b)

Output:

Hello World

Repetition

print("Hi " * 3)

Output:

Hi Hi Hi

Membership

s = "Python"

print("P" in s)
print("z" not in s)

18. IMPORTANT STRING FUNCTIONS AND METHODS

Function/MethodPurpose
len()Returns length
capitalize()Capitalizes first character
title()Converts words to title case
lower()Converts to lowercase
upper()Converts to uppercase
count()Counts occurrences
find()Finds position; returns -1 if absent
index()Finds position; raises error if absent
startswith()Checks starting text
endswith()Checks ending text
isalnum()Checks letters/digits
isalpha()Checks alphabetic characters
isdigit()Checks digits
islower()Checks lowercase
isupper()Checks uppercase
isspace()Checks whitespace
lstrip()Removes leading whitespace/characters
rstrip()Removes trailing whitespace/characters
strip()Removes leading and trailing whitespace/characters
replace()Replaces text
join()Joins strings
partition()Divides string into three parts
split()Splits string into a list

Example

s = "hello python"

print(s.upper())
print(s.title())
print(len(s))

19. LIST

A list is an ordered and mutable collection.

Lists use square brackets.

numbers = [10, 20, 30, 40]

Lists can contain different data types:

data = [10, "Python", 3.5, True]

20. LIST INDEXING

numbers = [10, 20, 30, 40, 50]

print(numbers[0])
print(numbers[2])
print(numbers[-1])

Output:

10
30
50

21. LIST OPERATIONS

Concatenation

a = [1, 2]
b = [3, 4]

print(a + b)

Output:

[1, 2, 3, 4]

Repetition

print([1, 2] * 3)

Output:

[1, 2, 1, 2, 1, 2]

Membership

numbers = [10, 20, 30]

print(20 in numbers)

Slicing

numbers = [10, 20, 30, 40, 50]

print(numbers[1:4])

Output:

[20, 30, 40]

22. IMPORTANT LIST FUNCTIONS AND METHODS

Function/MethodPurpose
len()Number of elements
list()Creates/converts to list
append()Adds one item at end
extend()Adds multiple items
insert()Adds item at specified index
count()Counts occurrences
index()Finds first occurrence
remove()Removes first matching value
pop()Removes and returns an item
reverse()Reverses list
sort()Sorts list in place
sorted()Returns sorted result
min()Smallest value
max()Largest value
sum()Total of numeric values

23. LIST MUTABILITY

Lists are mutable.

Example:

numbers = [10, 20, 30]

numbers[1] = 99

print(numbers)

Output:

[10, 99, 30]

24. TUPLE

A tuple is an ordered and immutable collection.

Example:

numbers = (10, 20, 30, 40)

Important

A tuple cannot normally be modified after creation.

numbers[1] = 99

This produces a TypeError.


25. TUPLE OPERATIONS

Indexing

t = (10, 20, 30)

print(t[1])

Concatenation

a = (1, 2)
b = (3, 4)

print(a + b)

Repetition

print((1, 2) * 2)

Membership

print(20 in (10, 20, 30))

Slicing

t = (10, 20, 30, 40)

print(t[1:3])

26. TUPLE FUNCTIONS AND METHODS

Function/MethodPurpose
len()Number of elements
tuple()Creates/converts to tuple
count()Counts occurrences
index()Finds first occurrence
sorted()Returns sorted list
min()Minimum
max()Maximum
sum()Sum

27. DICTIONARY

A dictionary stores data in key-value pairs.

Example:

student = {
    "name": "Amit",
    "age": 17,
    "marks": 85
}

Here:

"name"  → key
"Amit"  → value

"age"   → key
17      → value

28. ACCESSING DICTIONARY ITEMS

Use the key:

print(student["name"])
print(student["marks"])

Output:

Amit
85

Using get():

print(student.get("name"))

If the key is absent, get() can return None or a supplied default instead of raising KeyError.


29. MODIFYING A DICTIONARY

Dictionaries are mutable.

Add an Item

student["city"] = "Lucknow"

Modify an Item

student["marks"] = 90

Delete an Item

del student["age"]

30. TRAVERSING A DICTIONARY

Keys

for key in student:
    print(key)

Values

for value in student.values():
    print(value)

Keys and Values

for key, value in student.items():
    print(key, value)

31. IMPORTANT DICTIONARY METHODS

MethodPurpose
len()Number of key-value pairs
dict()Creates dictionary
keys()Returns keys
values()Returns values
items()Returns key-value pairs
get()Gets value for key
update()Adds/modifies items
delDeletes specified item
clear()Removes all items
fromkeys()Creates dictionary from keys
copy()Creates a copy
pop()Removes specified key
popitem()Removes last inserted pair
setdefault()Gets key or inserts default

32. OPERATORS

Operators are symbols or keywords used to perform operations on values.

Important categories:

  1. Arithmetic

  2. Relational

  3. Logical

  4. Assignment

  5. Augmented assignment

  6. Identity

  7. Membership


33. ARITHMETIC OPERATORS

OperatorMeaningExample
+Addition10 + 5
-Subtraction10 - 5
*Multiplication10 * 5
/Division10 / 5
//Floor division10 // 3
%Modulus10 % 3
**Exponentiation2 ** 3

34. RELATIONAL OPERATORS

Relational operators compare values and produce True or False.

<    Less than
>    Greater than
<=   Less than or equal to
>=   Greater than or equal to
==   Equal to
!=   Not equal to

Example:

a = 10
b = 20

print(a < b)

Output:

True

35. LOGICAL OPERATORS

Python has three main logical operators:

and
or
not

and

True only when both conditions are true.

print(10 > 5 and 20 > 10)

or

True when at least one condition is true.

print(10 > 20 or 20 > 10)

not

Reverses a Boolean result.

print(not True)

Output:

False

Precedence

Among these logical operators:

not
  ↓
and
  ↓
or

36. ASSIGNMENT OPERATORS

The basic assignment operator is:

=

Example:

x = 10

Other assignment operators include:

= 
+=
-=
*=
/=
%=
**=
//=

37. AUGMENTED ASSIGNMENT

Augmented assignment combines an operation with assignment.

Example:

x = 10

x += 5

Equivalent to:

x = x + 5

Other examples:

x -= 2
x *= 3
x /= 2
x %= 2

38. IDENTITY OPERATORS

Python provides:

is
is not

They test object identity, not value equality.

Example:

a = [1, 2]
b = a

print(a is b)

Output:

True

Important Difference

==  → compares values
is  → compares object identity

Do not normally use is when you simply want to compare ordinary values.


39. MEMBERSHIP OPERATORS

Python provides:

in
not in

They check whether an item belongs to a collection.

Example:

numbers = [10, 20, 30]

print(20 in numbers)
print(50 not in numbers)

Output:

True
True

40. EXPRESSIONS

An expression is a combination of values, variables, operators and function calls that produces a value.

Examples:

10 + 20
a * b
x > 10
"Hello" + "World"

Example:

a = 10
b = 20

result = a + b

Here:

a + b

is an expression.


41. STATEMENTS

A statement is an instruction that Python can execute.

Examples:

x = 10
print(x)

Conditional and loop constructs are also statements.

if x > 5:
    print("Greater")

42. OPERATOR PRECEDENCE

When an expression contains multiple operators, Python follows precedence rules.

A simplified order is:

()
**
+x, -x
*, /, //, %
+, -
comparisons
not
and
or

Example

result = 10 + 5 * 2

Multiplication is performed first.

Therefore:

5 * 2 = 10
10 + 10 = 20

Output:

20

Use Parentheses

To make the order clear:

result = (10 + 5) * 2

Output:

30

43. TYPE CONVERSION

Type conversion means changing a value from one data type to another.

There are two important forms:

  1. Implicit conversion

  2. Explicit conversion


44. IMPLICIT TYPE CONVERSION

Python automatically converts a value to a compatible type in certain expressions.

Example:

a = 10
b = 2.5

result = a + b

print(result)
print(type(result))

Output:

12.5
<class 'float'>

The integer is promoted to a floating-point value for the operation.


45. EXPLICIT TYPE CONVERSION

The programmer explicitly converts a value using functions such as:

int()
float()
str()
bool()
list()
tuple()

Example

x = "100"

y = int(x)

print(y)
print(type(y))

Output:

100
<class 'int'>

More Examples

int(3.8)      # 3
float(10)     # 10.0
str(100)      # "100"

46. INPUT FROM CONSOLE

The input() function accepts data from the user.

Example:

name = input("Enter your name: ")

print("Hello", name)

Important

input() returns the entered data as a string.

Therefore:

age = input("Enter age: ")

stores age as a string.

For numeric input:

age = int(input("Enter age: "))

47. OUTPUT USING print()

The print() function displays output.

name = "Amit"
age = 17

print(name)
print(age)

Multiple values:

print("Name:", name, "Age:", age)

48. ERRORS IN PYTHON

Three important categories studied in Class 11 are:

  1. Syntax errors

  2. Runtime errors

  3. Logical errors


49. SYNTAX ERROR

A syntax error occurs when the rules of Python syntax are violated.

Example:

if x > 10
    print(x)

The colon is missing.

Python reports a syntax-related error.


50. RUNTIME ERROR

A runtime error occurs while the program is executing.

Example:

a = 10
b = 0

print(a / b)

This produces:

ZeroDivisionError

Other examples include:

  • NameError

  • TypeError

  • ValueError

  • IndexError

  • KeyError


51. LOGICAL ERROR

A logical error occurs when the program runs but produces an incorrect result because the logic is wrong.

Example:

a = 10
b = 20

average = a + b / 2

print(average)

The intended formula should be:

average = (a + b) / 2

The first program may run successfully but give the wrong answer.


52. FLOW OF CONTROL

The flow of control describes the order in which statements are executed.

Main types:

  1. Sequential flow

  2. Conditional flow

  3. Iterative flow


53. SEQUENTIAL FLOW

In sequential execution, statements execute from top to bottom.

a = 10
b = 20
c = a + b

print(c)

Flow:

Start
  ↓
Input/Assignment
  ↓
Calculation
  ↓
Output
  ↓
End

54. INDENTATION

Indentation means spaces at the beginning of a line.

Python uses indentation to define blocks of code.

Example:

if age >= 18:
    print("Adult")

The indented statement belongs to the if block.

Incorrect indentation can cause an error.

Common Practice

Use 4 spaces for one indentation level.


55. CONDITIONAL FLOW

Conditional statements allow a program to make decisions.

Important statements:

if
if-else
if-elif-else

56. if STATEMENT

Syntax:

if condition:
    statement

Example:

age = 18

if age >= 18:
    print("Eligible")

57. if-else

Used when there are two alternatives.

age = 16

if age >= 18:
    print("Adult")
else:
    print("Minor")

58. if-elif-else

Used when there are multiple conditions.

marks = 75

if marks >= 90:
    print("A")
elif marks >= 75:
    print("B")
elif marks >= 60:
    print("C")
else:
    print("D")

Python checks the conditions from top to bottom and executes the first matching branch.


59. ITERATIVE FLOW

Iteration means repeatedly executing a block of code.

Python provides:

for loop
while loop

60. for LOOP

The for loop is commonly used to traverse a sequence or another iterable.

Example:

for i in range(1, 6):
    print(i)

Output:

1
2
3
4
5

61. range() FUNCTION

The range() function generates a sequence of numbers represented by a range object.

Forms

range(stop)
range(start, stop)
range(start, stop, step)

Example

range(5)

produces values:

0 1 2 3 4

The stop value is excluded.

Example

for i in range(2, 10, 2):
    print(i)

Output:

2
4
6
8

62. while LOOP

A while loop repeatedly executes a block while its condition is true.

Syntax:

while condition:
    statements

Example:

i = 1

while i <= 5:
    print(i)
    i += 1

Output:

1
2
3
4
5

63. break STATEMENT

break immediately terminates the nearest enclosing loop.

Example:

for i in range(1, 10):
    if i == 5:
        break
    print(i)

Output:

1
2
3
4

64. continue STATEMENT

continue skips the remaining statements in the current iteration and moves to the next iteration.

Example:

for i in range(1, 6):
    if i == 3:
        continue
    print(i)

Output:

1
2
4
5

65. NESTED LOOPS

A loop inside another loop is called a nested loop.

Example:

for i in range(1, 4):
    for j in range(1, 4):
        print(i, j)

Nested loops are commonly used for:

  • Patterns

  • Tables

  • Matrix processing

  • Two-dimensional data


66. PATTERN PROGRAM

Program: Print a Star Pattern

for i in range(1, 5):
    for j in range(i):
        print("*", end=" ")
    print()

Output:

*
* *
* * *
* * * *

67. SUM OF NUMBERS

Program to calculate sum from 1 to n:

n = int(input("Enter n: "))

total = 0

for i in range(1, n + 1):
    total += i

print("Sum =", total)

For n = 5:

Sum = 15

68. FACTORIAL

Factorial of a positive integer n is:

n! = n × (n-1) × (n-2) × ... × 1

Example:

5! = 5 × 4 × 3 × 2 × 1
   = 120

Program:

n = int(input("Enter a positive number: "))

fact = 1

for i in range(1, n + 1):
    fact *= i

print("Factorial =", fact)

69. ABSOLUTE VALUE

The absolute value of a number is its non-negative magnitude.

Examples:

|-10| = 10
|10|  = 10

Program using conditional statement:

n = int(input("Enter a number: "))

if n < 0:
    n = -n

print("Absolute value =", n)

70. SORTING THREE NUMBERS

A simple conditional approach:

a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
c = int(input("Enter third number: "))

if a > b:
    a, b = b, a

if b > c:
    b, c = c, b

if a > b:
    a, b = b, a

print("Ascending order:", a, b, c)

Example:

Input:
30
10
20

Output:
Ascending order: 10 20 30

71. DIVISIBILITY

A number is divisible by another number when the remainder is zero.

The modulus operator % is used.

Example:

n = int(input("Enter a number: "))

if n % 5 == 0:
    print("Divisible by 5")
else:
    print("Not divisible by 5")

72. STRING TRAVERSAL

A string can be traversed character by character using a loop.

s = "Python"

for ch in s:
    print(ch)

Output:

P
y
t
h
o
n

73. LIST TRAVERSAL

numbers = [10, 20, 30, 40]

for value in numbers:
    print(value)

74. TUPLE TRAVERSAL

numbers = (10, 20, 30, 40)

for value in numbers:
    print(value)

75. DICTIONARY TRAVERSAL

student = {
    "name": "Amit",
    "marks": 85
}

for key, value in student.items():
    print(key, value)

76. NESTED LISTS

A list containing another list is called a nested list.

data = [
    [10, 20],
    [30, 40],
    [50, 60]
]

Access:

print(data[0][1])

Output:

20

77. PYTHON MODULES

A module is a Python file containing reusable code such as functions, classes and variables.

Examples:

math
random
statistics

78. IMPORTING MODULES

Using import:

import math

print(math.sqrt(25))

Using from:

from math import sqrt

print(sqrt(25))

79. MATH MODULE

Important functions/constants:

math.pi
math.e
math.sqrt()
math.ceil()
math.floor()
math.pow()
math.fabs()
math.sin()
math.cos()
math.tan()

Example:

import math

print(math.sqrt(49))
print(math.ceil(4.2))
print(math.floor(4.8))

Output:

7.0
5
4

Trigonometric functions use radians.


80. RANDOM MODULE

Important functions:

random.random()
random.randint()
random.randrange()

Example:

import random

print(random.random())
print(random.randint(1, 10))
print(random.randrange(1, 10))

Remember:

randint(1,10)   → 1 to 10
randrange(1,10) → 1 to 9

81. STATISTICS MODULE

Important functions:

statistics.mean()
statistics.median()
statistics.mode()

Example:

import statistics

numbers = [10, 20, 20, 30, 40]

print(statistics.mean(numbers))
print(statistics.median(numbers))
print(statistics.mode(numbers))

82. LIST, TUPLE AND DICTIONARY

FeatureListTupleDictionary
Syntax[ ]( ){key:value}
OrderedYesYesYes
MutableYesNoYes
AccessIndexIndexKey
Duplicate valuesAllowedAllowedKeys unique
SlicingYesYesNo
Main useCollectionFixed collectionKey-value data

83. IMPORTANT PYTHON FUNCTIONS

FunctionPurpose
print()Displays output
input()Accepts input
type()Returns type
len()Returns length
int()Converts to integer
float()Converts to float
str()Converts to string
bool()Converts to Boolean
list()Creates/converts to list
tuple()Creates/converts to tuple
dict()Creates dictionary
min()Finds minimum
max()Finds maximum
sum()Calculates total
sorted()Returns sorted result
range()Generates a range of values

84. IMPORTANT PYTHON CONCEPTS TO REMEMBER

Variables

x = 10

Input

x = input()

Numeric Input

x = int(input())

Output

print(x)

Condition

if x > 0:
    print("Positive")

Loop

for i in range(5):
    print(i)

While

while condition:
    statement

List

a = [10, 20, 30]

Tuple

a = (10, 20, 30)

Dictionary

a = {"name": "Amit", "marks": 90}

Module

import math

85. IMPORTANT PROGRAMS FOR REVISION

Students should practise these programs before beginning advanced Class 12 topics.

Basic Programs

  1. Print Hello World.

  2. Add two numbers.

  3. Find area of a circle.

  4. Find simple interest.

  5. Convert temperature.

  6. Swap two numbers.

  7. Find maximum of two numbers.

  8. Find maximum of three numbers.

  9. Check positive, negative or zero.

  10. Check odd or even.

  11. Check divisibility.

  12. Calculate absolute value.

Loop Programs

  1. Print numbers from 1 to n.

  2. Print even numbers.

  3. Print odd numbers.

  4. Find sum of numbers.

  5. Find sum of even numbers.

  6. Find factorial.

  7. Generate multiplication table.

  8. Generate patterns.

  9. Count digits of a number.

  10. Reverse a number.

String Programs

  1. Count characters.

  2. Count vowels.

  3. Count spaces.

  4. Reverse a string.

  5. Check palindrome.

  6. Count occurrences of a character.

  7. Convert uppercase to lowercase.

  8. Search for a substring.

List Programs

  1. Find maximum and minimum.

  2. Calculate mean.

  3. Linear search.

  4. Count frequency.

  5. Sort a list.

  6. Reverse a list.

  7. Count even and odd elements.

Dictionary Programs

  1. Create a student dictionary.

  2. Create an employee-salary dictionary.

  3. Count character frequency.

  4. Add and modify dictionary elements.

  5. Traverse keys and values.


86. COMMON PYTHON ERRORS

ErrorExample Cause
SyntaxErrorIncorrect Python syntax
IndentationErrorIncorrect indentation
NameErrorUsing an undefined name
TypeErrorIncompatible operation between types
ValueErrorInvalid value for an operation/conversion
ZeroDivisionErrorDivision by zero
IndexErrorInvalid sequence index
KeyErrorMissing dictionary key

87. IMPORTANT DIFFERENCES FOR EXAM

= vs ==

=   → Assignment
==  → Equality comparison

Example:

x = 10

if x == 10:
    print("Equal")

== vs is

== → compares values
is → compares object identity

break vs continue

break    → Terminates the loop
continue → Skips current iteration

remove() vs pop()

remove(value) → Removes by value
pop(index)    → Removes by index and returns item

append() vs extend()

append([3,4]) → adds [3,4] as one item
extend([3,4]) → adds 3 and 4 separately

sort() vs sorted()

sort()   → Changes original list
sorted() → Returns a new sorted list

find() vs index()

find()  → returns -1 if substring is not found
index() → raises ValueError if substring is not found

List vs Tuple

List  → Mutable
Tuple → Immutable

88. PYTHON FLOW OF CONTROL – REVISION MAP

                  FLOW OF CONTROL
                         |
          ┌──────────────┼──────────────┐
          ↓              ↓              ↓
     Sequential     Conditional      Iterative
          |              |              |
       Normal         if             for
       execution      if-else         while
                      if-elif-else

89. COLLECTIONS REVISION MAP

                    COLLECTIONS
                         |
          ┌──────────────┼──────────────┐
          ↓              ↓              ↓
        LIST           TUPLE        DICTIONARY
          |              |              |
       Mutable        Immutable       Mutable
          |              |              |
       Index           Index            Key
       Slice           Slice          Key-Value

90. DATA TYPES REVISION MAP

                  PYTHON DATA TYPES
                         |
       ┌─────────┬───────┼────────┬─────────┐
       ↓         ↓       ↓        ↓         ↓
     Number    Boolean  String    List     Tuple
       |                             
   int/float/
    complex

                    Other Important Types
                           |
                    ┌──────┴──────┐
                    ↓             ↓
                 NoneType      Dictionary

91. FINAL QUICK REVISION

Python

Python = High-level, general-purpose programming language

Variable

x = 10

Input

input()

Output

print()

Decision

if / elif / else

Repetition

for / while

Loop Control

break / continue

List

Mutable collection

Tuple

Immutable collection

Dictionary

Key-value collection

String

Immutable sequence of characters

Module

Reusable Python code

92. IMPORTANT CBSE EXAM QUESTIONS

Very Short Answer Questions

  1. What is Python?

  2. Who developed Python?

  3. What is an identifier?

  4. What is a keyword?

  5. What is a literal?

  6. What is a variable?

  7. What is dynamic typing?

  8. What is a comment?

  9. What is the difference between interactive and script mode?

  10. What is a data type?

  11. Name three numeric data types in Python.

  12. What is a Boolean value?

  13. What is a string?

  14. What is a list?

  15. What is a tuple?

  16. What is a dictionary?

  17. What is mutability?

  18. What is an operator?

  19. What is an expression?

  20. What is a statement?

  21. What does input() return?

  22. What is type conversion?

  23. What is indentation?

  24. What is a syntax error?

  25. What is a runtime error?

  26. What is a logical error?

  27. What is the purpose of range()?

  28. What does break do?

  29. What does continue do?

  30. What is a nested loop?

  31. What is a module?

  32. What is the purpose of import?

  33. What is the difference between == and is?

  34. What is the difference between sort() and sorted()?


93. IMPORTANT OUTPUT-BASED QUESTIONS

Students should practise predicting the output of programs such as:

Question 1

x = 10
y = 3

print(x // y)
print(x % y)

Output:

3
1

Question 2

x = [10, 20, 30]

x.append(40)

print(x)

Output:

[10, 20, 30, 40]

Question 3

x = [10, 20]

x.extend([30, 40])

print(x)

Output:

[10, 20, 30, 40]

Question 4

for i in range(2, 7):
    print(i)

Output:

2
3
4
5
6

Question 5

for i in range(1, 6):
    if i == 3:
        continue
    print(i)

Output:

1
2
4
5

94. IMPORTANT PROGRAMMING PRACTICE

Before starting advanced Class 12 Python programming, a student should be able to independently write programs for:

✓ Input and output
✓ Arithmetic calculations
✓ Type conversion
✓ Conditions
✓ Nested conditions
✓ for loops
✓ while loops
✓ break and continue
✓ Strings
✓ Lists
✓ Tuples
✓ Dictionaries
✓ Searching
✓ Counting
✓ Frequency calculation
✓ Basic patterns
✓ Mathematical calculations
✓ Modules

95. FINAL REVISION CHECKLIST

A Class 12 student should be able to answer YES to all of the following:

□ I understand Python variables.
□ I know Python data types.
□ I can use input() and print().
□ I understand type conversion.
□ I know arithmetic and relational operators.
□ I understand logical operators.
□ I know == and is are different.
□ I understand if, if-else and if-elif-else.
□ I can use for and while loops.
□ I understand range().
□ I can use break and continue.
□ I can write nested loops.
□ I can work with strings.
□ I can work with lists.
□ I can work with tuples.
□ I can work with dictionaries.
□ I understand mutable and immutable objects.
□ I can perform searching and counting.
□ I can identify common Python errors.
□ I can import and use Python modules.

GOLDEN RULES FOR CLASS 12 PYTHON

1. Use correct indentation.
2. Remember that Python is case-sensitive.
3. input() returns a string.
4. Use int() or float() when numeric input is required.
5. Remember that range() excludes its stop value.
6. Use == for value comparison.
7. Use is for object identity.
8. Lists are mutable.
9. Tuples and strings are immutable.
10. Dictionary data is accessed using keys.
11. break terminates a loop.
12. continue skips the current iteration.
13. Check the difference between sort() and sorted().
14. Read error messages carefully.
15. Test programs with different inputs.

Final Summary

Class 11 Python concepts are the foundation of Class 12 Computer Science.

The most important areas to revise are:

Python Basics
      ↓
Variables & Data Types
      ↓
Operators & Expressions
      ↓
Input & Output
      ↓
Conditional Statements
      ↓
Loops
      ↓
Strings
      ↓
Lists
      ↓
Tuples
      ↓
Dictionaries
      ↓
Modules
      ↓
Problem Solving
      ↓
Class 12 Advanced Python

A strong understanding of these Class 11 concepts makes the advanced programming topics of Class 12 much easier to learn and apply.

 

CBSE Class 12 Computer Science (083)

Unit 1: Computational Thinking and Programming – 2

Topic: Functions in Python


1. Introduction to Functions

A function is a named block of reusable code that performs a specific task.

Instead of writing the same code again and again, we can place it inside a function and call the function whenever required.

Example

def greet():
    print("Hello Student!")

greet()
greet()

Output

Hello Student!
Hello Student!

The function greet() is executed two times by calling it two times.

Advantages of Functions

  1. Code Reusability – Write code once and use it many times.

  2. Modularity – Divide a large program into smaller parts.

  3. Easy Debugging – Errors can be located more easily.

  4. Easy Maintenance – Changes can be made in one place.

  5. Improved Readability – Programs become easier to understand.

  6. Avoids Repetition – Reduces duplicate code.


2. Types of Functions

Python functions can broadly be classified into:

                    FUNCTIONS
                        |
        +---------------+----------------+
        |               |                |
 Built-in Functions   Module Functions   User-defined
                                         Functions

A. Built-in Functions

These functions are already provided by Python.

We can use them directly without defining them.

Examples

print()
input()
len()
type()
int()
float()
str()
sum()
max()
min()
abs()
round()

Example

numbers = [10, 20, 30]

print(len(numbers))
print(sum(numbers))
print(max(numbers))

Output

3
60
30

3. Functions Defined in Modules

Python provides many modules containing useful functions.

A module is a file/library containing Python code such as functions, classes, and variables.

We generally import a module before using its functions.

Example: math Module

import math

print(math.sqrt(25))
print(math.factorial(5))

Output

5.0
120

Here:

  • math → module

  • sqrt() → function defined in the math module

  • factorial() → function defined in the math module

General Syntax

import module_name

module_name.function_name()

Example

import math

print(math.pow(2, 3))

Output:

8.0

4. User-Defined Functions

A user-defined function is a function created by the programmer according to the requirements of a program.

The keyword def is used to define a function.

Syntax

def function_name():
    statements

Example

def welcome():
    print("Welcome to Python")

welcome()

Output

Welcome to Python

5. Creating a User-Defined Function

A function definition contains:

  1. def keyword

  2. Function name

  3. Parentheses ()

  4. Colon :

  5. Function body

  6. Indentation

Example

def show_message():
    print("Python is easy to learn")
    print("Python is powerful")

show_message()

Output

Python is easy to learn
Python is powerful

6. Function Definition and Function Call

There are two important concepts:

Function Definition

It tells Python what the function should do.

def hello():
    print("Hello")

Function Call

It executes the function.

hello()

Complete Example

def hello():
    print("Hello Student")

hello()

Important

Defining a function does not execute its body.

The function executes only when it is called.


7. Parameters and Arguments

Parameters and arguments are used to pass data to a function.

Consider:

def add(a, b):
    print(a + b)

add(10, 20)

Here:

  • a and b are parameters.

  • 10 and 20 are arguments.

Parameter

A parameter is a variable written in the function definition.

def add(a, b):

a and b are parameters.

Argument

An argument is the actual value supplied when calling the function.

add(10, 20)

10 and 20 are arguments.

Easy Difference

ParameterArgument
Appears in function definitionAppears in function call
Acts as a placeholderProvides actual value
Example: a, bExample: 10, 20

8. Function with Parameters

A function can accept one or more parameters.

One Parameter

def square(n):
    print(n * n)

square(5)

Output:

25

Two Parameters

def add(a, b):
    print(a + b)

add(10, 20)

Output:

30

Three Parameters

def total(a, b, c):
    print(a + b + c)

total(10, 20, 30)

Output:

60

9. Positional Parameters / Positional Arguments

In a positional argument function call, arguments are matched with parameters according to their position.

Example

def student(name, age):
    print("Name:", name)
    print("Age:", age)

student("Rahul", 17)

Output:

Name: Rahul
Age: 17

Here:

"Rahul" → name
17      → age

The first argument is assigned to the first parameter, and the second argument is assigned to the second parameter.


Changing the Position

def divide(a, b):
    print(a / b)

divide(10, 2)

Output:

5.0

But:

divide(2, 10)

Output:

0.2

Therefore, position matters in positional arguments.


10. Default Parameters

A parameter can have a default value.

If the caller does not provide a value for that parameter, Python uses the default value.

Syntax

def function_name(parameter=default_value):
    statements

Example

def greet(name="Student"):
    print("Hello", name)

greet()
greet("Rahul")

Output

Hello Student
Hello Rahul

In the first call, no argument is supplied, so "Student" is used.

In the second call, "Rahul" replaces the default value.


11. Example of Default Parameters

def power(a, b=2):
    print(a ** b)

power(5)
power(5, 3)

Output

25
125

Explanation:

power(5)
     ↓
a = 5
b = 2 (default)
     ↓
5² = 25

And:

power(5, 3)
     ↓
a = 5
b = 3
     ↓
5³ = 125

12. Important Rule for Default Parameters

A parameter with a default value should generally come after non-default parameters.

Correct

def student(name, age=18):
    print(name, age)

Incorrect

def student(age=18, name):
    print(name, age)

This produces a syntax error because a non-default parameter cannot follow a default parameter.


13. Function Returning a Value

A function can send a result back to the place from where it was called.

The return statement is used for this purpose.

Example

def add(a, b):
    return a + b

result = add(10, 20)

print(result)

Output

30

Here:

add(10, 20)
      ↓
   10 + 20
      ↓
     30
      ↓
 return 30
      ↓
result = 30

14. return Statement

The return statement:

  1. Sends a value back to the caller.

  2. Ends the execution of the function at that point.

  3. Can return an expression/result.

Example

def square(n):
    return n * n

x = square(6)
print(x)

Output:

36

15. print() vs return

This is an important examination concept.

Using print()

def add(a, b):
    print(a + b)

add(10, 20)

The function displays the result.

Using return

def add(a, b):
    return a + b

x = add(10, 20)
print(x)

The function returns the result, which can be stored and used later.

Difference

print()return
Displays outputSends value back to caller
Mainly used for displaying informationUsed to provide a result
Returned value is not automatically available to callerReturned value can be stored in a variable
Does not return the calculated result to the caller in the same wayEnds the function and returns a value

16. Function Returning Multiple Values

Python allows a function to return multiple values.

Example

def calculate(a, b):
    return a + b, a - b

x, y = calculate(20, 5)

print("Sum =", x)
print("Difference =", y)

Output

Sum = 25
Difference = 15

Conceptually, Python returns the values together as a tuple:

return a + b, a - b

is equivalent in effect to returning:

(a + b, a - b)

17. Example: Returning Sum and Product

def calculate(a, b):
    s = a + b
    p = a * b
    return s, p

sum_value, product = calculate(5, 4)

print("Sum =", sum_value)
print("Product =", product)

Output

Sum = 9
Product = 20

18. Function Without Return Statement

A function does not have to contain a return statement.

Example

def message():
    print("Welcome")

message()

The function performs its task and does not explicitly return a useful value.

If a Python function reaches the end without a return value, it returns None.

Example

def test():
    print("Hello")

x = test()

print(x)

Output:

Hello
None

19. Function with No Parameter and No Return

def message():
    print("Good Morning")

message()

20. Function with Parameter but No Return

def square(n):
    print(n * n)

square(5)

Output:

25

21. Function with No Parameter but Returning a Value

def get_number():
    return 100

x = get_number()

print(x)

Output:

100

22. Function with Parameters and Return Value

This is one of the most commonly used forms.

def multiply(a, b):
    return a * b

result = multiply(6, 7)

print(result)

Output:

42

23. Four Common Forms of Functions

ParametersReturn ValueExample
NoNodef show(): print("Hi")
YesNodef show(n): print(n)
NoYesdef get(): return 10
YesYesdef add(a,b): return a+b

24. Practical Example: Find Even or Odd

def check_even_odd(n):
    if n % 2 == 0:
        return "Even"
    else:
        return "Odd"

result = check_even_odd(15)

print(result)

Output

Odd

25. Practical Example: Find Maximum of Two Numbers

def maximum(a, b):
    if a > b:
        return a
    else:
        return b

print(maximum(25, 18))

Output

25

26. Practical Example: Calculate Factorial

def factorial(n):
    fact = 1

    for i in range(1, n + 1):
        fact = fact * i

    return fact

print(factorial(5))

Output

120

27. Practical Example: Calculate Area of Circle

def area_circle(r):
    return 3.14 * r * r

radius = float(input("Enter radius: "))

area = area_circle(radius)

print("Area =", area)

28. Practical Example: Default Parameter

def interest(principal, rate=5):
    return principal * rate / 100

print(interest(10000))
print(interest(10000, 8))

Output

500.0
800.0

29. Function Calling Another Function

A function can call another function.

Example

def square(n):
    return n * n

def display(n):
    print("Square =", square(n))

display(5)

Output

Square = 25

30. Local Variables in Functions

A variable created inside a function is generally a local variable.

def show():
    x = 10
    print(x)

show()

Here x is created inside show().

Its scope is limited to the function.


31. Important Terminology

Function

A reusable block of code that performs a particular task.

Function Definition

The code used to create a function.

def add(a, b):
    return a + b

Function Call

The statement used to execute a function.

add(10, 20)

Parameter

A variable specified in a function definition.

def add(a, b):

Argument

The actual value passed to a function.

add(10, 20)

Default Parameter

A parameter that has a predefined value.

def greet(name="Student"):

Return Value

The value sent back by a function using return.


32. Important Differences

Built-in Function vs User-Defined Function

Built-in FunctionUser-Defined Function
Already provided by PythonCreated by programmer
No need to define it before useMust be defined before use
Example: len()Example: add()
Performs commonly required tasksPerforms tasks according to program requirements

Parameter vs Argument

ParameterArgument
Used in function definitionUsed in function call
Placeholder variableActual value
a, b in def add(a,b)10, 20 in add(10,20)

Print vs Return

print()return
Displays dataReturns data
Used for outputUsed to send result to caller
Cannot be used as a substitute for returning a valueReturned result can be assigned to a variable
Execution continues after print()Function execution ends when return is executed

33. Function Execution Flow

Consider:

def add(a, b):
    return a + b

x = add(10, 20)

print(x)

Execution:

Program starts
     |
     v
Function definition
     |
     v
add(10, 20) called
     |
     v
a = 10, b = 20
     |
     v
a + b
     |
     v
return 30
     |
     v
x = 30
     |
     v
print(x)
     |
     v
Output: 30

34. Important Rules of Functions

  1. Use the def keyword to define a function.

  2. Function names should follow Python identifier rules.

  3. Function body must be properly indented.

  4. A function executes when it is called.

  5. Parameters receive values supplied as arguments.

  6. Positional arguments are matched according to their position.

  7. Default parameters provide values when arguments are omitted.

  8. A return statement sends a value back to the caller.

  9. A function can return more than one value.

  10. If no value is explicitly returned, the function returns None.


35. Quick Revision

FUNCTIONS
   |
   +-- Built-in Functions
   |      |
   |      +-- print()
   |      +-- len()
   |      +-- type()
   |      +-- sum()
   |
   +-- Module Functions
   |      |
   |      +-- math.sqrt()
   |      +-- math.factorial()
   |
   +-- User-Defined Functions
          |
          +-- def
          +-- Parameters
          +-- Arguments
          +-- Default Parameters
          +-- Positional Arguments
          +-- return

36. Important Board Examination Questions

Very Short Answer Questions

  1. What is a function?

  2. What is the purpose of the def keyword?

  3. What is a built-in function?

  4. Give two examples of built-in functions.

  5. What is a module function?

  6. What is a user-defined function?

  7. Define parameter.

  8. Define argument.

  9. What is a default parameter?

  10. What is the purpose of the return statement?


Short Answer Questions

  1. Differentiate between built-in functions and user-defined functions.

  2. Differentiate between parameters and arguments.

  3. Explain positional arguments with an example.

  4. What are default parameters? Give an example.

  5. Differentiate between print() and return.

  6. Explain the four common forms of user-defined functions.

  7. What happens if a function does not explicitly return a value?

  8. Explain how a function can return multiple values.


37. Programming Questions for Practice

Program 1

Create a function to calculate the square of a number.

Program 2

Create a function to find whether a number is even or odd.

Program 3

Create a function to calculate the factorial of a number.

Program 4

Create a function to find the maximum of three numbers.

Program 5

Create a function to calculate the area of a circle.

Program 6

Create a function that accepts two numbers and returns their sum and product.

Program 7

Create a function using a default parameter to calculate simple interest.

Program 8

Create a function that accepts a number and returns whether it is positive, negative, or zero.


38. Golden Rules to Remember

def → Define a function

Function call → Execute a function

Parameter → Variable in function definition

Argument → Actual value in function call

Default parameter → Predefined value

Positional argument → Matched according to position

return → Sends result back to caller

No explicit return value → None

Multiple return values → Can be collected into multiple variables


Final Summary

A function is one of the most important concepts in Python programming. Functions allow a large program to be divided into smaller, reusable modules.

The three important categories are:

  • Built-in functions – provided directly by Python.

  • Functions defined in modules – provided by modules such as math.

  • User-defined functions – created by the programmer using def.

For CBSE examinations, special attention should be given to:

function definition, function call, parameters, arguments, positional arguments, default parameters, and return values.

 

CBSE Class 12 Computer Science (083)

Unit 1: Computational Thinking and Programming – 2

Topics Covered

  1. Flow of Execution

  2. Scope of a Variable

    • Global Scope

    • Local Scope

  3. Exception Handling

    • try

    • except

    • finally

  4. Introduction to Files

  5. Types of Files

    • Text File

    • Binary File

    • CSV File

  6. Relative and Absolute Paths

  7. Text File Handling

  8. Binary File Handling using pickle

  9. CSV File Handling using csv

  10. Data Structure – Stack

  11. Stack Operations

  • Push

  • Pop

  1. Implementation of Stack using List


1. Flow of Execution

The flow of execution refers to the order in which statements of a Python program are executed.

Normally, Python executes statements from top to bottom, but the flow can change because of:

  • Function calls

  • Conditional statements

  • Loops

  • break

  • continue

  • return

  • Exception handling


Example 1: Sequential Flow

print("A")
print("B")
print("C")

Output

A
B
C

The statements execute in the same order in which they are written.

print("A")
     ↓
print("B")
     ↓
print("C")

2. Flow of Execution with Function

Consider:

def message():
    print("Inside function")

print("Start")
message()
print("End")

Output

Start
Inside function
End

Flow

Program starts
      |
      v
Function definition
      |
      v
print("Start")
      |
      v
message() called
      |
      v
Function body executes
      |
      v
print("End")

Important Point

When Python encounters a function definition, it defines the function but does not execute its body immediately.

The function body executes when the function is called.


3. Flow of Execution with return

def add(a, b):
    result = a + b
    return result

x = add(10, 20)
print(x)

Execution:

add(10,20)
     ↓
a = 10, b = 20
     ↓
result = 30
     ↓
return 30
     ↓
x = 30
     ↓
print(x)

Output:

30

The return statement sends control back to the statement from where the function was called.


4. Scope of a Variable

The scope of a variable is the region of a program where that variable can be accessed or used.

Python mainly uses:

  1. Global Scope

  2. Local Scope


5. Global Scope

A variable created outside all functions has global scope.

It can generally be accessed from different parts of the program, including inside functions for reading.

Example

x = 100

def show():
    print(x)

show()
print(x)

Output

100
100

Here x is a global variable.


6. Local Scope

A variable created inside a function has local scope.

It can normally be accessed only inside that function.

Example

def show():
    x = 50
    print(x)

show()

Output:

50

But:

def show():
    x = 50

show()
print(x)

This produces an error because x is local to show().


7. Global vs Local Variables

x = 100

def test():
    y = 200
    print(x)
    print(y)

test()

print(x)

Here:

  • x → Global variable

  • y → Local variable

Scope Diagram

                 PROGRAM
                    |
          +---------+---------+
          |                   |
      Global Scope        Function
                              |
                         Local Scope

8. Global Variable Modified Inside a Function

If we want to modify a global variable inside a function, Python provides the global keyword.

Example

x = 10

def change():
    global x
    x = 20

change()

print(x)

Output

20

Without global, an assignment such as x = 20 inside the function would create a local variable named x rather than modify the global one.


9. Local and Global Variable with Same Name

x = 10

def show():
    x = 20
    print("Inside:", x)

show()

print("Outside:", x)

Output

Inside: 20
Outside: 10

The local variable hides the global variable inside the function.


10. Exception Handling

An exception is an error or unexpected event that occurs during program execution and interrupts the normal flow of the program.

Examples:

  • Dividing by zero

  • Converting invalid text to an integer

  • Accessing a missing list index

  • Opening a file that does not exist


11. Why Exception Handling is Required

Consider:

a = 10
b = 0

print(a / b)

print("Program completed")

The program generates a ZeroDivisionError, and the later statement is not executed.

Exception handling allows us to handle such situations gracefully.


12. try-except

The try block contains code that may produce an exception.

The except block handles the exception.

Syntax

try:
    statements
except:
    statements

Example

try:
    a = 10
    b = 0
    print(a / b)
except:
    print("Division by zero is not allowed")

Output

Division by zero is not allowed

13. Handling a Specific Exception

It is better to specify the expected exception when possible.

try:
    a = 10
    b = 0
    print(a / b)
except ZeroDivisionError:
    print("Cannot divide by zero")

14. Common Python Exceptions

ExceptionCommon Cause
ZeroDivisionErrorDivision by zero
ValueErrorInvalid value
TypeErrorIncompatible data types
IndexErrorInvalid list/string index
KeyErrorMissing dictionary key
FileNotFoundErrorFile does not exist
NameErrorUndefined variable

15. Example: ValueError

try:
    n = int(input("Enter a number: "))
    print(n)
except ValueError:
    print("Please enter a valid integer")

If the user enters:

abc

Output:

Please enter a valid integer

16. Multiple except Blocks

A program can have more than one except block.

try:
    a = int(input("Enter number: "))
    b = int(input("Enter divisor: "))
    print(a / b)

except ValueError:
    print("Invalid input")

except ZeroDivisionError:
    print("Cannot divide by zero")

17. finally Block

The finally block contains statements that should execute whether an exception occurs or not.

Syntax

try:
    statements
except:
    statements
finally:
    statements

Example

try:
    a = 10
    b = 2
    print(a / b)

except ZeroDivisionError:
    print("Cannot divide by zero")

finally:
    print("Program finished")

Output

5.0
Program finished

18. Example of finally with Exception

try:
    print(10 / 0)

except ZeroDivisionError:
    print("Error occurred")

finally:
    print("This will execute")

Output:

Error occurred
This will execute

19. try-except-finally Flow

              try block
                  |
          +-------+-------+
          |               |
      No error         Exception
          |               |
          |            except
          |               |
          +-------+-------+
                  |
               finally
                  |
                End

20. Introduction to Files

A file is a collection of data stored permanently on a storage device.

Files allow programs to store data even after the program terminates.

Examples:

  • Student records

  • Marks

  • Employee information

  • Text documents

  • Images

  • Audio

  • Videos


21. Why Files are Required

Variables store data temporarily in memory.

Files provide permanent storage.

Program
   |
   v
Data
   |
   v
File
   |
   v
Permanent Storage

22. Types of Files

The important file types in the CBSE syllabus are:

  1. Text File

  2. Binary File

  3. CSV File


23. Text File

A text file stores data in the form of characters that can normally be read by humans.

Examples:

students.txt
notes.txt
marks.txt

Example content:

Rahul
Amit
Priya

24. Binary File

A binary file stores data in binary form.

Examples include:

  • Images

  • Audio

  • Video

  • Serialized Python objects

In CBSE Python file handling, the pickle module is commonly used to store Python objects in binary files.

Example:

students.dat
records.dat

25. CSV File

CSV stands for:

Comma-Separated Values

A CSV file stores tabular data using rows and columns.

Example:

Name,Age,Marks
Rahul,17,85
Amit,18,90
Priya,17,92

CSV files are commonly used for exchanging data between spreadsheet and database applications.


26. Text vs Binary vs CSV

Text FileBinary FileCSV File
Stores character/text dataStores binary dataStores tabular data
Human-readableUsually not directly human-readableHuman-readable
Example .txtExample .datExample .csv
Uses text modesUses binary modesUses csv module
read(), write()pickle.dump(), pickle.load()writer(), reader()

27. File Paths

A file path tells the operating system where a file is located.

There are two important types:

  1. Absolute Path

  2. Relative Path


28. Absolute Path

An absolute path gives the complete location of a file.

Example in Windows:

C:\Users\Student\Documents\data.txt

Example in Linux:

/home/student/data.txt

The path starts from the root/drive location.


29. Relative Path

A relative path specifies a file location relative to the current working directory.

Suppose the program is running from:

C:\Python\Project

and the file is:

C:\Python\Project\data.txt

Then:

open("data.txt")

uses a relative path.


30. Absolute vs Relative Path

Absolute PathRelative Path
Complete locationLocation relative to current directory
Usually longerUsually shorter
Example C:\Data\a.txtExample a.txt
Independent of current working directoryDepends on current working directory

31. Text File Handling

Python provides the built-in open() function to open files.

Syntax

file_object = open(filename, mode)

Example:

f = open("data.txt", "r")

Here:

  • f → file object

  • "data.txt" → file name

  • "r" → read mode


32. Text File Open Modes

The important text file modes are:

  • r

  • r+

  • w

  • w+

  • a

  • a+


r – Read

Opens an existing file for reading.

f = open("data.txt", "r")

Important:

  • File must exist.

  • Reading is allowed.

  • Writing is not allowed.


r+ – Read and Write

Opens an existing file for both reading and writing.

f = open("data.txt", "r+")

Important:

  • File must already exist.

  • Reading and writing are allowed.

  • Existing content is not automatically deleted.


w – Write

Opens a file for writing.

f = open("data.txt", "w")

Important:

  • Creates the file if it does not exist.

  • If the file exists, its previous contents are truncated/erased.

Example

f = open("data.txt", "w")
f.write("Hello")
f.close()

w+ – Write and Read

Opens a file for both writing and reading.

f = open("data.txt", "w+")

Important:

  • Creates file if necessary.

  • Existing contents are truncated.


a – Append

Opens a file for adding data at the end.

f = open("data.txt", "a")

Important:

  • Creates the file if it does not exist.

  • Existing data is preserved.

  • New data is written at the end.


a+ – Append and Read

Opens a file for both appending and reading.

f = open("data.txt", "a+")

Important:

  • Creates the file if necessary.

  • Existing data is preserved.

  • Writing occurs at the end.


33. File Mode Summary

ModeReadWriteCreates if MissingTruncates Existing
rYesNoNoNo
r+YesYesNoNo
wNoYesYesYes
w+YesYesYesYes
aNoYesYesNo
a+YesYesYesNo

Exam Tip

Remember:

r  → read
w  → write (old contents removed)
a  → append (add at end)
+  → read + write capability

34. Closing a Text File

After completing file operations, a file should be closed.

f = open("data.txt", "r")

data = f.read()

print(data)

f.close()

The close() method closes the file.


35. Opening a File Using with Clause

The with statement is a safer and convenient way to work with files.

Syntax

with open("data.txt", "r") as f:
    data = f.read()
    print(data)

When the with block finishes, Python automatically closes the file.

Advantage

There is no need to explicitly write:

f.close()

36. Writing Data using write()

The write() method writes a string to a text file.

f = open("data.txt", "w")

f.write("Hello Python")

f.close()

The file will contain:

Hello Python

37. Writing Multiple Lines using write()

f = open("data.txt", "w")

f.write("Apple\n")
f.write("Mango\n")
f.write("Orange\n")

f.close()

File content:

Apple
Mango
Orange

The \n represents a newline.


38. writelines()

The writelines() method writes multiple strings to a file.

Example

f = open("data.txt", "w")

lines = ["Apple\n", "Mango\n", "Orange\n"]

f.writelines(lines)

f.close()

39. write() vs writelines()

write()writelines()
Writes one stringWrites multiple strings from an iterable
Example f.write("Hello")Example f.writelines(["A\n", "B\n"])
Does not automatically add newlineDoes not automatically add newline

Important

writelines() does not automatically add \n.

Therefore:

["A\n", "B\n"]

is different from:

["A", "B"]

40. Reading Data using read()

The read() method reads data from a text file.

f = open("data.txt", "r")

data = f.read()

print(data)

f.close()

It reads the entire remaining file by default.


Reading a Specific Number of Characters

f = open("data.txt", "r")

data = f.read(5)

print(data)

f.close()

This reads up to 5 characters from the current file position.


41. readline()

The readline() method reads one line at a time.

f = open("data.txt", "r")

line = f.readline()

print(line)

f.close()

42. Reading Multiple Lines using readline()

f = open("data.txt", "r")

print(f.readline())
print(f.readline())
print(f.readline())

f.close()

Each call reads the next line from the current file position.


43. readlines()

The readlines() method reads the remaining lines and returns them as a list.

f = open("data.txt", "r")

lines = f.readlines()

print(lines)

f.close()

Possible output:

['Apple\n', 'Mango\n', 'Orange\n']

44. read() vs readline() vs readlines()

MethodPurposeResult
read()Reads entire remaining content or specified charactersString
readline()Reads one lineString
readlines()Reads remaining linesList of strings

45. Reading a File using with

with open("data.txt", "r") as f:
    data = f.read()

print(data)

This is recommended because the file is automatically closed after the block.


46. tell() Method

The tell() method returns the current position of the file pointer.

Example

f = open("data.txt", "r")

print(f.tell())

f.read(5)

print(f.tell())

f.close()

If the first five characters are read, the file pointer generally moves forward by five positions in a simple text-file example.


47. seek() Method

The seek() method changes the position of the file pointer.

Syntax

f.seek(position)

Example

f = open("data.txt", "r")

f.seek(0)

data = f.read()

print(data)

f.close()

seek(0) moves the file pointer to the beginning.


48. seek() and tell() Together

f = open("data.txt", "r")

print(f.tell())

f.read(5)

print(f.tell())

f.seek(0)

print(f.tell())

f.close()

Conceptually:

Beginning
   |
   | read(5)
   v
Position 5
   |
   | seek(0)
   v
Beginning

49. Manipulation of Data in a Text File

Data can be manipulated by:

  • Reading the existing content

  • Searching for data

  • Replacing data

  • Adding new data

  • Rewriting modified content

Example: Replace a Word

Suppose data.txt contains:

Python is easy.
Python is powerful.

Program:

with open("data.txt", "r") as f:
    data = f.read()

data = data.replace("Python", "Programming")

with open("data.txt", "w") as f:
    f.write(data)

New content:

Programming is easy.
Programming is powerful.

50. Example: Count a Word in a Text File

with open("data.txt", "r") as f:
    data = f.read()

count = data.lower().count("python")

print("Python occurs", count, "times")

51. Example: Append Data to Text File

with open("students.txt", "a") as f:
    f.write("Rahul\n")

The new name is added at the end of the file.


52. Binary File Handling

A binary file stores information in binary form.

Python's pickle module can be used to store and retrieve Python objects in binary files.

First import the module:

import pickle

53. Binary File Modes

The important binary modes are:

  • rb

  • rb+

  • wb

  • wb+

  • ab

  • ab+

Here b means binary.


54. Meaning of Binary Modes

ModeMeaning
rbRead binary
rb+Read and write binary
wbWrite binary
wb+Write and read binary
abAppend binary
ab+Append and read binary

Important

r + b = read binary
w + b = write binary
a + b = append binary

55. pickle.dump()

The dump() method stores a Python object in a binary file.

Syntax

pickle.dump(object, file_object)

Example

import pickle

student = {
    "roll": 101,
    "name": "Rahul",
    "marks": 85
}

with open("student.dat", "wb") as f:
    pickle.dump(student, f)

The dictionary is stored in binary form.


56. pickle.load()

The load() method retrieves an object from a binary file.

Example

import pickle

with open("student.dat", "rb") as f:
    student = pickle.load(f)

print(student)

Possible output:

{'roll': 101, 'name': 'Rahul', 'marks': 85}

57. dump() vs load()

dump()load()
Stores objectRetrieves object
Used for writingUsed for reading
Usually used with wb/abUsually used with rb
pickle.dump(obj, f)pickle.load(f)

58. Creating/Writing a Binary File

import pickle

students = [
    [101, "Rahul", 85],
    [102, "Amit", 90],
    [103, "Priya", 92]
]

with open("students.dat", "wb") as f:
    for student in students:
        pickle.dump(student, f)

59. Reading a Binary File

If multiple objects were stored using dump(), they can be read one by one using load().

import pickle

with open("students.dat", "rb") as f:
    try:
        while True:
            student = pickle.load(f)
            print(student)
    except EOFError:
        pass

Output

[101, 'Rahul', 85]
[102, 'Amit', 90]
[103, 'Priya', 92]

EOFError indicates that the end of the file has been reached while repeatedly loading objects.


60. Searching a Record in a Binary File

Suppose the file contains student records:

import pickle

roll = int(input("Enter roll number: "))
found = False

with open("students.dat", "rb") as f:
    try:
        while True:
            student = pickle.load(f)

            if student[0] == roll:
                print("Record found:", student)
                found = True
                break

    except EOFError:
        pass

if not found:
    print("Record not found")

61. Appending a Record to a Binary File

Use append binary mode ab.

import pickle

student = [104, "Ravi", 88]

with open("students.dat", "ab") as f:
    pickle.dump(student, f)

The new record is added at the end.


62. Updating a Binary File

A common approach to update a binary file is:

  1. Read all records.

  2. Find the required record.

  3. Modify the record.

  4. Rewrite the file.

Example

import pickle

records = []

with open("students.dat", "rb") as f:
    try:
        while True:
            record = pickle.load(f)

            if record[0] == 102:
                record[2] = 95

            records.append(record)

    except EOFError:
        pass

with open("students.dat", "wb") as f:
    for record in records:
        pickle.dump(record, f)

This updates the marks of roll number 102.


63. Binary File Operations

The important operations are:

Binary File
    |
    +-- Create
    |
    +-- Read
    |
    +-- Write
    |
    +-- Search
    |
    +-- Append
    |
    +-- Update

64. CSV File Handling

CSV stands for:

Comma-Separated Values

Python provides the csv module for working with CSV files.

Import it using:

import csv

65. Creating/Writing a CSV File

Example

import csv

with open("students.csv", "w", newline="") as f:
    writer = csv.writer(f)

    writer.writerow(["Roll", "Name", "Marks"])
    writer.writerow([101, "Rahul", 85])
    writer.writerow([102, "Amit", 90])

The CSV file will contain:

Roll,Name,Marks
101,Rahul,85
102,Amit,90

66. writer()

The csv.writer() function creates a writer object.

Syntax

writer = csv.writer(file_object)

Example:

writer = csv.writer(f)

67. writerow()

writerow() writes one row.

writer.writerow(["101", "Rahul", "85"])

68. writerows()

writerows() writes multiple rows.

rows = [
    [101, "Rahul", 85],
    [102, "Amit", 90],
    [103, "Priya", 92]
]

writer.writerows(rows)

69. writerow() vs writerows()

writerow()writerows()
Writes one rowWrites multiple rows
Takes one rowTakes an iterable of rows
Example writer.writerow(row)Example writer.writerows(rows)

70. Reading a CSV File

Use csv.reader().

import csv

with open("students.csv", "r", newline="") as f:
    reader = csv.reader(f)

    for row in reader:
        print(row)

Possible output:

['Roll', 'Name', 'Marks']
['101', 'Rahul', '85']
['102', 'Amit', '90']

CSV reader returns values as strings unless the program converts them to other data types.


71. Searching in a CSV File

import csv

roll = input("Enter roll number: ")
found = False

with open("students.csv", "r", newline="") as f:
    reader = csv.reader(f)

    next(reader)   # Skip header

    for row in reader:
        if row[0] == roll:
            print("Record found:", row)
            found = True
            break

if not found:
    print("Record not found")

72. Closing a CSV File

A CSV file can be closed using:

f.close()

When using:

with open(...) as f:

the file is automatically closed after the block.


73. Text, Binary and CSV File Comparison

FeatureTextBinaryCSV
Main data formCharactersBinary/object dataRows and columns
ModuleUsually built-in file methodspicklecsv
Common extension.txt.dat.csv
Writewrite() / writelines()pickle.dump()writerow() / writerows()
Readread() / readline() / readlines()pickle.load()reader()
Human readableYesUsually noYes

74. Data Structure

A data structure is a way of organising and storing data so that it can be accessed and manipulated efficiently.

Examples:

  • List

  • Tuple

  • Dictionary

  • Stack

  • Queue

For the CBSE Class 12 syllabus, an important data structure is the Stack.


75. Stack

A stack is a linear data structure in which insertion and deletion take place at the same end.

This end is called the TOP.

A stack follows:

LIFO

Last In, First Out

The element inserted last is removed first.


76. Real-Life Example of Stack

Think about a stack of plates.

        +---------+
TOP →   | Plate 4 |
        +---------+
        | Plate 3 |
        +---------+
        | Plate 2 |
        +---------+
        | Plate 1 |
        +---------+

If Plate 4 was placed last, it will be removed first.

Therefore:

Last In → First Out

77. Stack Operations

The two fundamental stack operations are:

  1. Push

  2. Pop


78. Push Operation

Push means inserting an element into the stack.

Example:

Before PUSH 30:

TOP
 |
 v
+----+
| 20 |
+----+
| 10 |
+----+

After PUSH 30:

TOP
 |
 v
+----+
| 30 |
+----+
| 20 |
+----+
| 10 |
+----+

79. Pop Operation

Pop means removing the top element from the stack.

Example:

Before POP:

TOP
 |
 v
+----+
| 30 |
+----+
| 20 |
+----+
| 10 |
+----+

After POP:

Removed = 30

TOP
 |
 v
+----+
| 20 |
+----+
| 10 |
+----+

80. Stack using Python List

Python's list can be used to implement a stack.

Consider:

stack = []

The list represents an empty stack.


81. Push using append()

Use the append() method to push an element.

stack = []

stack.append(10)
stack.append(20)
stack.append(30)

print(stack)

Output:

[10, 20, 30]

Here 30 is at the top.

TOP → 30
      20
      10

82. Pop using pop()

The pop() method removes and returns the last element.

stack = [10, 20, 30]

item = stack.pop()

print("Deleted:", item)
print("Stack:", stack)

Output:

Deleted: 30
Stack: [10, 20]

83. Basic Stack Program

stack = []

stack.append(10)
stack.append(20)
stack.append(30)

print("Stack:", stack)

item = stack.pop()

print("Popped:", item)
print("Stack after pop:", stack)

Output:

Stack: [10, 20, 30]
Popped: 30
Stack after pop: [10, 20]

84. Stack Underflow

If we try to pop an element from an empty stack, an error occurs.

stack = []

stack.pop()

This produces:

IndexError

This situation is called stack underflow.

Therefore, always check whether the stack is empty before popping.

if len(stack) == 0:
    print("Stack Underflow")
else:
    print("Popped:", stack.pop())

85. Checking Whether Stack is Empty

Two common approaches are:

if len(stack) == 0:
    print("Empty")

or:

if not stack:
    print("Empty")

For CBSE-level programs, len(stack) == 0 is often easier for beginners to understand.


86. Menu-Driven Stack Program

stack = []

while True:
    print("\n1. PUSH")
    print("2. POP")
    print("3. DISPLAY")
    print("4. EXIT")

    choice = int(input("Enter choice: "))

    if choice == 1:
        item = int(input("Enter item: "))
        stack.append(item)
        print("Item pushed successfully")

    elif choice == 2:
        if len(stack) == 0:
            print("Stack Underflow")
        else:
            print("Popped item:", stack.pop())

    elif choice == 3:
        if len(stack) == 0:
            print("Stack is empty")
        else:
            print("Stack:", stack)

    elif choice == 4:
        print("Program ended")
        break

    else:
        print("Invalid choice")

87. Stack Flowchart Concept

             Start
               |
               v
          Display Menu
               |
        +------+------+
        |      |      |
       PUSH   POP   DISPLAY
        |      |      |
        v      v      v
     append() pop()  print()
        |      |      |
        +------+------+
               |
               v
            Continue?
             /    \
           Yes     No
            |       |
            +       v
                  Stop

88. Important Stack Terms

Stack

A linear data structure following LIFO.

TOP

The position from which insertion and deletion occur.

Push

Insertion of an element into a stack.

Pop

Deletion of the top element.

Underflow

Attempt to pop from an empty stack.

LIFO

Last In, First Out.


89. Important Stack Questions

Very Short Questions

  1. What is a stack?

  2. What is LIFO?

  3. What is the TOP of a stack?

  4. What is push operation?

  5. What is pop operation?

  6. Which Python list method is used to implement push?

  7. Which Python list method is used to implement pop?

  8. What is stack underflow?


Short Answer Questions

  1. Explain stack with a suitable example.

  2. Explain push and pop operations.

  3. How can a stack be implemented using a Python list?

  4. Differentiate between push and pop.

  5. What happens when pop() is performed on an empty stack?

  6. Write a Python program to implement a menu-driven stack.


90. Important File Handling Questions

  1. What is a file?

  2. Why is file handling required?

  3. Differentiate between text and binary files.

  4. What is a CSV file?

  5. What is an absolute path?

  6. What is a relative path?

  7. Explain the different text file modes.

  8. Differentiate between r, w and a.

  9. What is the purpose of the with statement?

  10. What is the use of read()?

  11. Differentiate between read(), readline() and readlines().

  12. What is the use of seek()?

  13. What is the use of tell()?

  14. What is the purpose of pickle?

  15. Differentiate between dump() and load().

  16. What is csv.writer()?

  17. Differentiate between writerow() and writerows().

  18. How is a CSV file read in Python?

  19. Write a program to search a record in a binary file.

  20. Write a program to append a record to a binary file.


91. Important Exception Handling Questions

  1. What is an exception?

  2. Why is exception handling required?

  3. What is the purpose of try?

  4. What is the purpose of except?

  5. What is the purpose of finally?

  6. Write a program to handle ZeroDivisionError.

  7. Write a program to handle ValueError.

  8. Name any four common Python exceptions.


92. Quick Revision Table

TopicImportant Point
Flow of executionOrder in which statements execute
Global variableDefined outside functions
Local variableDefined inside a function
globalUsed to modify a global variable from a function
ExceptionRuntime event/error disrupting normal execution
tryContains risky code
exceptHandles exception
finallyExecutes whether exception occurs or not
Text fileStores character data
Binary fileStores binary/object data
CSV fileStores tabular data
Absolute pathComplete file location
Relative pathLocation relative to current directory
read()Reads content
readline()Reads one line
readlines()Reads lines into a list
write()Writes a string
writelines()Writes multiple strings
seek()Changes file pointer position
tell()Gives current file pointer position
pickle.dump()Stores Python object
pickle.load()Retrieves Python object
csv.writer()Creates CSV writer
writerow()Writes one CSV row
writerows()Writes multiple CSV rows
StackLIFO data structure
PushInsert into stack
PopRemove top element
append()Used for stack push
pop()Used for stack pop

93. Must-Remember CBSE Points

Functions

def → defines function
call → executes function
parameter → variable in definition
argument → actual value in call
return → sends result back

Scope

Global → outside function
Local  → inside function

Exception Handling

try → risky code
except → handles error
finally → executes at the end

Text Files

r  → read
r+ → read + write
w  → write + truncate
w+ → read + write + truncate
a  → append
a+ → read + append

Binary Files

rb  → read binary
rb+ → read + write binary
wb  → write binary
wb+ → read + write binary
ab  → append binary
ab+ → read + append binary

Binary File

pickle.dump() → write/store object
pickle.load() → read/retrieve object

CSV

csv.writer() → create writer
writerow()   → one row
writerows()  → multiple rows
csv.reader() → read rows

Stack

Push → append()
Pop  → pop()
Rule → LIFO

94. Final Concept Map

              COMPUTATIONAL THINKING & PROGRAMMING
                           |
        +------------------+------------------+
        |                  |                  |
      Functions          Files             Data Structure
        |                  |                  |
   +----+----+       +-----+-----+          Stack
   |    |    |       |     |     |            |
 Built-in Module User  Text Binary CSV      LIFO
             Defined   |     |     |           |
                       |     |     |       +----+----+
                    read/write pickle csv  Push    Pop
                       |       |     |       |       |
                    seek/   dump/load reader append pop
                    tell

Final Summary

In this part of Class 12 Computer Science (083), students learn how Python controls program execution, manages variable scope, handles runtime exceptions, works with different types of files, and implements a basic data structure.

The most important practical areas for examination are:

  • Global and local variables

  • try-except-finally

  • Text file modes

  • read(), readline(), readlines()

  • write() and writelines()

  • seek() and tell()

  • Binary files with pickle

  • dump() and load()

  • Searching, appending and updating binary records

  • CSV files with csv.reader() and csv.writer()

  • Stack implementation using Python lists

  • append() for push

  • pop() for pop

  • LIFO principle

  • Stack underflow

These concepts form an important practical and theory portion of CBSE Class 12 Computer Science (083)

 

 

एक टिप्पणी भेजें

0 टिप्पणियाँ
* Please Don't Spam Here. All the Comments are Reviewed by Admin.