CHAPTER PDF
Complete curriculum textbook chapter document for reading and offline study.
NOTES
Complete conceptual breakdown, formulas, diagrams, and memory aids.
Brief Overview of Python
Complete chapter notes based on the supplied 2026–27 textbook PDF. Includes every chapter heading, definitions, syntax, examples, program outputs, revision points, textbook exercise solutions and the SMIS case study.
Learning outcomes
After studying this chapter, a learner should be able to explain Python and its execution modes, identify keywords and valid identifiers, create variables, recognise common data types, use operators and expressions, accept and display data, identify programming errors, understand functions, write conditional statements and use for, range and nested loops.
Python, shell, scripts, keywords, identifiers, variables and comments.
Numbers, strings, lists, tuples, dictionaries, operators and expressions.
Input/output, functions, debugging and conditional statements.
for loops, range() and nested loops.
3.1 Introduction to Python
A program is an ordered set of instructions or commands executed by a computer. A programming language is a language used to specify instructions to a computer. Examples include Python, C, C++ and Java.
Python is a popular, easy-to-learn, high-level programming language created by Guido van Rossum in 1991. It is used in software development, web development, scientific computing, Big Data and Artificial Intelligence.
Important characteristics of Python
- High-level language: Its statements are relatively easy for humans to read and write.
- Interpreted language: Python code is executed by the Python interpreter.
- Open-source: Python is available for use and distribution under an open-source licence.
- General-purpose: It can be used to build many kinds of applications.
- Readable syntax: Its syntax is designed to be readable; indentation defines blocks of code.
3.1.1 Working with Python
To write and execute a Python program, a Python interpreter must be installed on the computer. Alternatively, an online Python interpreter can be used. The interpreter is also called the Python shell.
The symbol >>> is the Python prompt. It indicates that the interpreter is ready to receive instructions.
>>> 10 + 20
30
>>> print("Hello Python")
Hello Python
The latest Python version can be downloaded from the official website: https://www.python.org/.
3.1.2 Execution Modes
There are two ways to run a program using the Python interpreter:
- Interactive mode
- Script mode
(A) Interactive Mode
In interactive mode, a Python statement is typed directly at the >>> prompt. When Enter is pressed, the interpreter executes the statement and displays the result immediately.
>>> 5 + 7
12
>>> print("Welcome to Python")
Welcome to Python
Advantage: It is convenient for testing a single line of code and obtaining an instant result.
Limitation: Statements are not automatically saved for future use. To execute them again, the statements may need to be retyped.
(B) Script Mode
In script mode, a Python program is written in a file, saved and then executed using the interpreter. Such files have the .py extension and are called scripts.
Python includes a built-in editor called IDLE – Integrated Development and Learning Environment. A script can also be created using another code editor.
Steps to create and execute a script in IDLE
- Open IDLE.
- Select File → New File.
- Write the Python program in the editor.
- Save it with a filename ending in
.py, such asprog3_1.py. - Select Run → Run Module.
- The output appears in the Python Shell.
# prog3_1.py
print("Save Earth")
print("Preserve Nature")Output:Save Earth
Preserve Nature
| Interactive mode | Script mode |
|---|---|
| Statements are typed at the Python prompt. | Statements are written and saved in a .py file. |
| Each statement is executed immediately. | The saved program is executed as a script. |
| Useful for quick tests and short commands. | Useful for longer programs and future reuse. |
3.2 Python Keywords
Keywords are reserved words. Each keyword has a specific, predefined meaning to the Python interpreter. A keyword cannot be used as an ordinary variable or function name. Python is case-sensitive, so keywords must be written exactly as defined.
The Python 3.7 keyword list shown in the textbook is:
False class finally is return
None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
assert else import pass
break except in raise
True, False and None are written with the exact capitalisation shown. Words such as if, else, for and while are lowercase.3.3 Identifiers
An identifier is a name used to identify a variable, function or another entity in a program.
Rules for naming identifiers
- An identifier must begin with an uppercase letter, lowercase letter or underscore (
_). - After the first character, it may contain letters (A–Z or a–z), digits (0–9) and underscores.
- An identifier cannot start with a digit.
- It can be of any length, but short and meaningful names are preferred.
- A Python keyword or reserved word cannot be used as an identifier.
- Special symbols such as
!,@,#,$and%are not allowed. - Spaces and hyphens are not allowed.
| Identifier | Valid? | Reason |
|---|---|---|
marksMaths | Yes | Begins with a letter and contains letters. |
_total | Yes | May begin with underscore. |
Total_Marks | Yes | Letters and underscore are allowed. |
1stRoom | No | Begins with a digit. |
total-Marks | No | Hyphen is not allowed. |
Total Marks | No | Contains a space. |
class | No | It is a Python keyword. |
Choosing meaningful identifiers
To calculate the average marks in Maths, English and Informatics Practices, use names such as marksMaths, marksEnglish, marksIP and avg rather than vague names such as a, b and c.
marksMaths = 80
marksEnglish = 75
marksIP = 90
avg = (marksMaths + marksEnglish + marksIP) / 3
print(avg)
3.4 Variables and Comments
Variables
A variable is an identifier whose value can change. For example, a variable named age can have different values for different people. A variable name should be unique within its scope in a program.
In Python, an assignment statement creates a variable and assigns a value to it.
Syntax
variable_name = value
Examples:
gender = 'M'
message = "Keep Smiling"
price = 987.9
age = 17
A variable may refer to a string, number or other Python value. A variable must be assigned a value before it is used; using an unassigned name causes an error. Wherever a variable name occurs in an expression, Python uses the value associated with that name.
Program 3-2: Sum of two numbers
# To find the sum of two given numbers
num1 = 10
num2 = 20
result = num1 + num2
print(result)Output: 30
Program 3-3: Area of a rectangle
Given length = 10 units and breadth = 20 units. Formula: Area = length × breadth.
# To find the area of a rectangle
length = 10
breadth = 20
area = length * breadth
print(area)Output: 200
Comments
A comment is a remark or note added to source code to make it easier for humans to understand. Comments are not executed by the interpreter. They document the meaning and purpose of code.
A single-line comment begins with the hash symbol #. Everything from the hash symbol to the end of that line is ignored by the interpreter.
# This is a comment
total = 10 + 20 # Calculate the total
print(total)
3.5 Data Types
Every value in Python belongs to a specific data type. A data type identifies the kind of data a variable can hold and the operations that can be performed on that data.
The textbook's Figure 3.6 (page 36) groups the Python data types into the following broad categories:
| Category | Types / examples |
|---|---|
| Numbers | int, float, complex, bool |
| Sequences | String, List, Tuple |
| Mapping | Dictionary |
| Set | Set |
| None | None (NoneType) |
Use the built-in type() function to determine the type of a value or variable.
quantity = 10
print(type(quantity)) # <class 'int'>
price = 1921.9
print(type(price)) # <class 'float'>
Simple data types such as integer, float and Boolean generally hold a single value. To store multiple values, Python provides sequence types such as strings, lists and tuples, and the mapping type dictionary.
3.5.1 Number
The Number data type stores numerical values. It is classified into three types: int, float and complex.
| Type | Description | Examples |
|---|---|---|
int | Integer numbers, without a fractional part. | -12, -3, 0, 123, 2 |
float | Floating-point numbers, usually containing a decimal point. | -2.04, 4.0, 14.23 |
complex | Complex numbers with real and imaginary parts. Python uses j for the imaginary unit. | 3 + 4j, 2 - 2j |
Boolean data type (bool)
The Boolean type bool is a subtype of integer and consists of two constants: True and False. In numeric contexts, True behaves like 1 and False behaves like 0.
is_present = True
print(type(is_present)) # <class 'bool'>
print(int(True)) # 1
print(int(False)) # 0
Using type()
>>> quantity = 10
>>> type(quantity)
<class 'int'>
>>> price = -1921.9
>>> type(price)
<class 'float'>
3.5.2 Sequence
A Python sequence is an ordered collection of items in which each item is indexed by an integer value. The three sequence types covered in this chapter are String, List and Tuple.
(A) String
A string is a group or sequence of characters. These characters may be alphabets, digits, special characters or spaces. String values are enclosed in single quotation marks or double quotation marks. The quotation marks mark the beginning and end of the string; they are not part of the stored string.
str1 = 'Hello Friend'
str2 = "452"
print(str1)
print(str2)
str2 is a numeric string because its characters look like a number, but its data type is still string. Numerical operations cannot be performed on it directly as if it were an integer.
print("45" + "2") # 452: string concatenation
print(int("45") + 2) # 47: numeric addition
(B) List
A list is a sequence of items separated by commas and enclosed in square brackets [ ]. Items in a list may belong to different data types.
# Create a list
list1 = [5, 3.4, "New Delhi", "20C", 45]
print(list1)Output:[5, 3.4, 'New Delhi', '20C', 45]
Lists are ordered and mutable (their items can be changed). Indexing starts at 0.
fruits = ["Apple", "Banana", "Mango"]
print(fruits[0]) # Apple
fruits[1] = "Orange"
print(fruits) # ['Apple', 'Orange', 'Mango']
(C) Tuple
A tuple is a sequence of comma-separated items enclosed in parentheses ( ). Its items may be of different data types. Once a tuple is created, its items cannot be changed; a tuple is immutable.
# Create and display a tuple
tuple1 = (10, 20, "Apple", 3.4, 'a')
print(tuple1)
print(tuple1[2])Output:(10, 20, 'Apple', 3.4, 'a')
Apple
String vs List vs Tuple
| Feature | String | List | Tuple |
|---|---|---|---|
| Enclosure | Single/double quotes | Square brackets [ ] | Parentheses ( ) |
| Contents | Characters | Items of different types possible | Items of different types possible |
| Order | Ordered | Ordered | Ordered |
| Mutable? | No | Yes | No |
| Example | "Hello" | [10, "A"] | (10, "A") |
3.5.3 Mapping – Dictionary
Mapping is an unordered data type in the textbook's description. The standard mapping type introduced here is the dictionary.
A dictionary stores data items in key-value pairs enclosed in curly brackets { }. A colon separates each key from its value. Each key-value pair is separated by a comma. A value is accessed by specifying its key inside square brackets.
Syntax
dictionary_name = {
key1: value1,
key2: value2
}
Keys are commonly strings in the chapter's examples; values can be of any data type. Dictionary keys must be unique.
Example 3.4 – Create a dictionary
dict1 = {
'Fruit': 'Apple',
'Climate': 'Cold',
'Price(kg)': 120
}
print(dict1)
print(dict1['Price(kg)'])Output:{'Fruit': 'Apple', 'Climate': 'Cold', 'Price(kg)': 120}
120
Accessing a value using a key
student = {
"name": "Riya",
"class": 11,
"marks": 88
}
print(student["name"])
print(student["marks"])Output:Riya
88
student["name"].String comparison note from the textbook
Python compares strings lexicographically (dictionary-like order), using the character code values. It compares the first characters; if they are equal, it compares the next characters, and continues until a difference is found or the strings end.
3.6 Operators
An operator performs a specific mathematical or logical operation on values. The values on which an operator works are called operands. For example, in 10 + num, 10 and num are operands and + is the operator.
3.6.1 Arithmetic Operators
Arithmetic operators perform addition, subtraction, multiplication, division, modulus, floor division and exponentiation.
| Operator | Operation | Description | Example |
|---|---|---|---|
+ | Addition | Adds two numeric values. | 5 + 6 = 11 |
- | Subtraction | Subtracts right operand from left. | 5 - 6 = -1 |
* | Multiplication | Multiplies two values. | 5 * 6 = 30 |
/ | Division | Divides left operand by right; returns quotient. | 5 / 2 = 2.5 |
% | Modulus | Returns the remainder. | 13 % 5 = 3 |
// | Floor division | Returns the quotient rounded down. | 5 // 2 = 2 |
** | Exponent | Raises the base to the power of the exponent. | 3 ** 4 = 81 |
num1 = 13
num2 = 5
print(num1 + num2) # 18
print(num1 - num2) # 8
print(num1 * num2) # 65
print(num1 / num2) # 2.6
print(num1 % num2) # 3
print(num1 // num2) # 2
print(num1 ** num2) # 371293
Arithmetic operators with strings and sequences
+joins (concatenates) two strings.*repeats a string when the other operand is an integer.- The textbook notes that
+and*work in similar ways for other sequence types such as lists and tuples.
str1 = "Hello"
str2 = "India"
print(str1 + str2) # HelloIndia
str1 = "India"
print(str1 * 2) # IndiaIndia
3.6.2 Relational Operators
Relational operators compare the values of two operands. The result is either True or False.
| Operator | Meaning | Example |
|---|---|---|
== | Equal to | 10 == 10 → True |
!= | Not equal to | 10 != 0 → True |
> | Greater than | 10 > 0 → True |
< | Less than | 10 < 10 → False |
>= | Greater than or equal to | 10 >= 10 → True |
<= | Less than or equal to | 5 <= 10 → True |
num1 = 10
num2 = 0
num3 = 10
print(num1 == num2) # False
print(num1 != num2) # True
print(num1 != num3) # False
print(num1 > num2) # True
print(num1 < num3) # False
The textbook also explains that Python compares strings lexicographically.
3.6.3 Assignment Operators
An assignment operator assigns or changes the value of the variable on its left side.
| Operator | Equivalent expression | Example (x=10, y=2) | New x |
|---|---|---|---|
= | Assign value | x = y | 2 |
+= | x = x + y | x += y | 12 |
-= | x = x - y | x -= y | 8 |
*= | x = x * y | x *= y | 20 |
/= | x = x / y | x /= y | 5.0 |
%= | x = x % y | x %= y | 0 |
//= | x = x // y | x //= y | 5 |
**= | x = x ** y | x **= y | 100 |
x += y is equivalent to x = x + y. Similarly, x -= y is equivalent to x = x - y.3.6.4 Logical Operators
Python supports three logical operators: and, or and not. They must be written in lowercase. In condition testing, they evaluate logical expressions to True or False.
| Operator | Meaning | Rule | Example |
|---|---|---|---|
and | Logical AND | True only if both conditions are True. | 10 == 10 and 2 == 2 → True |
or | Logical OR | True if at least one condition is True. | 10 > 5 or 2 > 10 → True |
not | Logical NOT | Reverses the truth value. | not (10 == 20) → True |
3.6.5 Membership Operators
Membership operators check whether a value is present in a sequence.
| Operator | Meaning | Example |
|---|---|---|
in | Returns True if a value is found in the sequence; otherwise False. | 2 in [1,2,3] → True |
not in | Returns True if a value is not found in the sequence. | 10 not in [1,2,3] → True |
numSeq = [1, 2, 3]
print(2 in numSeq) # True
print('1' in numSeq) # False: '1' is a string
print(10 not in numSeq) # True
print(1 not in numSeq) # False
3.7 Expressions
An expression is a combination of constants, variables and operators. An expression always evaluates to a value. A single value or a standalone variable is also an expression, but a standalone operator is not an expression.
Examples of valid expressions:
num - 20.43.0 + 3.1423 / 3 - 5 * 7 * (14 - 2)"Global" + "Citizen"
3.7.1 Precedence of Operators
Operator precedence is the order or hierarchy that determines which operator is applied first when an expression contains more than one operator. An operator with higher precedence is evaluated before one with lower precedence.
- Multiplication (
*) and division (/) have higher precedence than addition (+) and subtraction (-). - Parentheses
( )can override the normal precedence; the expression inside parentheses is evaluated first. - For operators with equal precedence, the textbook's examples describe evaluation from left to right. Python has specific exceptions for some operators, such as exponentiation.
Example 3.5
20 + 30 * 40
= 20 + 1200 # multiplication first
= 1220
Example 3.6
(20 + 30) * 40
= 50 * 40 # parentheses first
= 2000
Example 3.7
15.0 / 4.0 + (8 + 3.0)
= 15.0 / 4.0 + (8.0 + 3.0)
= 15.0 / 4.0 + 11.0
= 3.75 + 11.0
= 14.75
3.8 Input and Output
input() function
The input() function accepts data entered by the user through an input device such as a keyboard. It displays an optional prompt and accepts the entered data as a string, whether the user enters letters, numbers or special characters.
Syntax
variable = input([Prompt])The prompt is optional. Python takes the characters entered by the user, converts them to a string and assigns that string to the variable on the left side of =.
Example 3.8 – Accept name and age
fname = input("Enter your first name: ")
age = input("Enter your age: ")
print(fname)
print(age)
print(type(age))If the user enters Arnab and 19, then fname contains the string "Arnab" and age contains the string "19".
Type conversion using int()
To use numeric input in arithmetic, convert the input string to an appropriate numeric type. The int() function converts a valid integer string to an integer. A non-numeric or invalid integer string causes an error.
# Convert input string to integer
age = int(input("Enter your age: "))
print(type(age))Output for input 19: <class 'int'>
Similarly, float() converts suitable numeric text into a floating-point number.
print() function
The print() function displays data on the standard output device, normally the screen. It evaluates the expression before displaying the result.
Syntax
print(value)Example 3.10
| Statement | Output |
|---|---|
print("Hello") | Hello |
print(10 * 2.5) | 25.0 |
Complete example – square of a number
# Calculate square of a number
num = int(input("Enter the first number: "))
square = num * num
print("The square of", num, "is", square)
input() receives data as a string; int() or float() converts numeric input; print() displays the result.3.9 Debugging
Due to errors, a program may fail to execute or may generate an incorrect output. The chapter identifies three types of errors: syntax errors, logical errors and runtime errors.
3.9.1 Syntax Errors
A syntax error occurs when a program violates the rules (syntax) of Python. The interpreter can execute a statement only if it is syntactically correct. For example, parentheses must be in pairs.
# Incorrect: missing closing parenthesis
print(10 + 12
# Correct
print(10 + 12)If a syntax error is present, Python displays an error message and cannot execute the program normally until the error is corrected.
3.9.2 Logical Errors
A logical error (also called a bug or semantic error in this context) does not necessarily stop execution. The program runs but behaves incorrectly and produces an undesired result. Such errors can be difficult to identify because the code is syntactically valid.
# Incorrect formula
average = 10 + 12 / 2
print(average) # 16.0
# Correct formula
average = (10 + 12) / 2
print(average) # 11.0The incorrect expression divides 12 by 2 before adding 10. Parentheses make Python calculate the sum first.3.9.3 Runtime Errors
A runtime error causes abnormal termination while a program is executing. The statement may be syntactically correct, but the interpreter cannot complete the operation.
num1 = 10
num2 = 0
print(num1 / num2)This causes a ZeroDivisionError because division by zero is not allowed.
Debugging
Debugging is the process of identifying and removing logical and runtime errors so that the program runs successfully and produces the desired output.
| Error | Meaning | Example |
|---|---|---|
| Syntax | Code breaks Python's grammar rules. | Missing bracket or colon. |
| Logical | Program runs but result is wrong. | Incorrect average formula. |
| Runtime | Error occurs while the program is running. | Division by zero. |
3.10 Functions
A function is a set of statements or instructions grouped under a name to perform a specified task. A function can be defined once and reused at multiple places by calling its name. Functions reduce repetition and save time and effort.
Why are functions useful?
Suppose a program needs to calculate compound interest at several places. Instead of writing the same formula repeatedly, the calculation can be placed in a function such as CalcCompInt. The function can then be called whenever the calculation is required.
Built-in functions
Python provides predefined functions called built-in functions. The chapter has already introduced print() and input(). Other examples include len(), type(), int(), float(), max() and sum().
Modules
A module is a Python file in which multiple functions can be grouped. A module can be used in a program by importing it with the import statement.
import math
print(math.sqrt(25))Output: 5.0
Function name, arguments and return value
- Function name: The name used to identify and call a function.
- Arguments: Values passed to a function inside parentheses when it is called. A function may have zero, one or more arguments.
- Return value: A value sent back by the function to the calling point. Some functions do not return a value.
Table 3.8 – Common built-in functions
| Category | Functions listed in the textbook |
|---|---|
| Input / Output | input(), print() |
| Data type conversion | bool(), chr(), dict(), float(), int(), list(), ord(), set(), str(), tuple() |
| Mathematical | abs(), divmod(), max(), min(), pow(), sum() |
| Other | __import__(), len(), range(), type() |
Example – square using built-in functions
# Calculate square of a number
num = int(input("Enter the first number: "))
square = num * num
print("The square of", num, "is", square)
Here, input() accepts a value, int() converts the entered text into an integer, and print() displays the result. The values passed inside parentheses are arguments.
Additional illustration – user-defined function
The chapter introduces the concept of reusable functions. This additional example demonstrates how a programmer can define one.
def calculate_square(number):
result = number * number
return result
answer = calculate_square(5)
print(answer)Output: 25def defines the function, number is a parameter, and return sends the calculated value back.
3.11 if..else Statements
Normally, statements in a program execute one after another. Sometimes a program must choose between different actions depending on a condition. Conditional statements allow the program to take different paths according to the result of a condition.
(A) if statement
An if statement executes its indented body only when the condition is True.
Syntax
if condition:
statement(s)
Example 3.11 – Voting eligibility
age = int(input("Enter your age: "))
if age >= 18:
print("Eligible to vote")If the age is 18 or more, the message is displayed. If the condition is False, the body is skipped.
(B) if...else statement
The if...else statement executes the if block when the condition is True; otherwise, it executes the else block.
Syntax
if condition:
statements_when_true
else:
statements_when_false
Example – Difference between two numbers
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if num1 > num2:
diff = num1 - num2
else:
diff = num2 - num1
print("The difference of", num1, "and", num2, "is", diff)For inputs 5 and 6, the output is The difference of 5 and 6 is 1.
(C) if...elif...else statement
The elif (else-if) clause checks another condition when the preceding if or elif condition is False. Multiple elif clauses may be used. The else block is optional and executes when none of the preceding conditions is True.
Syntax
if condition1:
statements
elif condition2:
statements
elif condition3:
statements
else:
statements
Example 3.12 – Positive, negative or zero
number = int(input("Enter a number: "))
if number > 0:
print("Number is positive")
elif number < 0:
print("Number is negative")
else:
print("Number is zero")
Flow of an if-elif-else chain
If a condition is True, its corresponding indented block executes and the if statement terminates. Otherwise, the next condition is checked. After the conditional structure, execution continues with statements outside it.
Indentation
Indentation means leading whitespace (spaces or tabs) at the beginning of a statement. Python uses indentation to group statements into blocks, including nested blocks. Statements at the same indentation level belong to the same block. Incorrect indentation can cause a syntax error or change the intended program structure.
Difference between elif and else
| elif | else |
|---|---|
| Checks another condition. | Provides a default block when all preceding conditions are False. |
| Must be followed by a condition and colon. | Does not have a condition. |
| Zero or more elif clauses may be used. | At most one final else block is used in an if chain. |
3.12 for Loop
A loop or iteration repeats a set of statements. The for statement iterates over a range of values or a sequence. The loop body executes once for each item. The items may be numeric values, characters of a string, or elements of a list or tuple.
When all items have been processed, the interpreter starts executing the statements immediately after the loop. A for loop is useful when the sequence or range to be processed is known.
Syntax of for loop
for control_variable in sequence:
statements_inside_loop_body
Program 3-4 – Print even numbers in a sequence
# Print even numbers in the given sequence
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for num in numbers:
if (num % 2) == 0:
print(num, "is an even Number")Output:2 is an even Number
4 is an even Number
6 is an even Number
8 is an even Number
10 is an even Number
The loop takes one number at a time from the list. The expression num % 2 finds the remainder after division by 2. If that remainder is 0, the number is even.
for statement. The nested if body is indented one additional level.3.12.1 The range() Function
range() is a built-in Python function used to generate a sequence of integers. It is commonly used with a for loop.
Syntax
range([start], stop[, step])
- start: Optional starting value. If omitted, it defaults to 0.
- stop: Required stopping boundary. The stop value is excluded.
- step: Optional difference between consecutive values. If omitted, it defaults to 1.
- All arguments must be integers.
- The step can be positive or negative, but it cannot be zero.
Example 3.13 – range() examples
| Expression | Sequence | Explanation |
|---|---|---|
list(range(10)) | [0,1,2,3,4,5,6,7,8,9] | Starts at 0; stops before 10. |
list(range(2,10)) | [2,3,4,5,6,7,8,9] | Starts at 2; stops before 10. |
list(range(0,30,5)) | [0,5,10,15,20,25] | Increases by 5 each time. |
list(range(0,-9,-1)) | [0,-1,-2,-3,-4,-5,-6,-7,-8] | Decreases by 1; stops before -9. |
Program 3-5 – Multiples of 10
# Print multiples of 10 for numbers in a range
for num in range(5):
if num > 0:
print(num * 10)Output:10
20
30
40
Additional practice examples
# Print 1 to 5
for i in range(1, 6):
print(i)
# Print even numbers from 2 to 10
for i in range(2, 11, 2):
print(i)
# Count backwards from 5 to 1
for i in range(5, 0, -1):
print(i)
range(1, 6) does not include 6. The stop value is always excluded.3.13 Nested Loops
A nested loop is a loop placed inside another loop. The inner loop completes all its iterations for every one iteration of the outer loop.
General structure
for outer_variable in outer_sequence:
outer_loop_statements
for inner_variable in inner_sequence:
inner_loop_statements
statements_after_inner_loop
Program 3-6 – Demonstrate nested for loops
# Demonstrate working of nested for loops
for var1 in range(3):
print("Iteration " + str(var1 + 1) + " of outer loop")
for var2 in range(2): # nested / inner loop
print(var2 + 1)
print("Out of inner loop")
print("Out of outer loop")Output:Iteration 1 of outer loop
1
2
Out of inner loop
Iteration 2 of outer loop
1
2
Out of inner loop
Iteration 3 of outer loop
1
2
Out of inner loop
Out of outer loop
Understanding the execution
- The outer loop runs 3 times because
range(3)generates 0, 1 and 2. - For each outer iteration, the inner loop runs 2 times because
range(2)generates 0 and 1. - The inner loop body therefore runs 3 × 2 = 6 times.
Out of inner loopis printed once after each complete inner loop.Out of outer loopis printed once after the outer loop finishes.
Chapter Summary – Quick Revision
- Python is an open-source, high-level, interpreter-based language used for scientific and non-scientific computing.
- Interactive mode executes statements at the Python prompt; script mode runs a saved
.pyfile. - Comments are non-executable remarks beginning with
#. - An identifier is a user-defined name for a variable, function or other program entity.
- A variable is an identifier whose value can change. Assign a value before using it.
- Python data types include integer, Boolean, float, complex, string, list, tuple, set, None and dictionary.
- Operators manipulate operands. Operators may be unary or binary.
- An expression is a combination of values, variables and operators that evaluates to a value.
input()accepts user input;print()displays output.- Debugging is the process of identifying and removing errors.
- The
ifstatement is used for decision-making. - Looping allows sections of code to execute repeatedly.
- A for statement iterates over a range of values or a sequence.
- The body of a for loop executes until the range or sequence is exhausted.
Important syntax at a glance
| Purpose | Syntax |
|---|---|
| Assignment | variable = value |
| Input | variable = input("Prompt") |
| Integer input | number = int(input("Enter: ")) |
| Output | print(value) |
| if | if condition: |
| if-else | if condition: ... else: ... |
| if-elif-else | if c1: ... elif c2: ... else: ... |
| for loop | for item in sequence: |
| range | range(start, stop, step) |
| Nested loop | for outer in sequence: for inner in sequence: |
Textbook Exercise – Answers with Explanation
Exercise questions are from the supplied PDF, printed pages 51–53. The answers below preserve the intent of the questions and explain errors or ambiguities in the printed statements.
1. Identify invalid identifiers and explain why
| Identifier | Answer | Reason |
|---|---|---|
a) Serial_no. | Invalid | Period (.) is not allowed. |
b) 1st_Room | Invalid | Begins with a digit. |
c) Hundred$ | Invalid | Dollar sign is not allowed. |
d) Total Marks | Invalid | Contains a space. |
e) Total_Marks | Valid | Letters and underscore are allowed. |
f) total-marks | Invalid | Hyphen is not allowed. |
g) _Percentage | Valid | An identifier may begin with underscore. |
h) True | Invalid as an identifier | It is a reserved Boolean constant. |
2. Write the corresponding Python assignment statements
# (a) Assign values to length and breadth
length = 10
breadth = 20
# (b) Average of length and breadth assigned to sum
sum = (length + breadth) / 2
# (c) Create the stationery list
stationery = ["Paper", "Gel Pen", "Eraser"]
# (d) Assign name parts
first = "Mohandas"
middle = "Karamchand"
last = "Gandhi"
# (e) Concatenate name parts with spaces
fullname = first + " " + middle + " " + last
Note: The textbook specifically asks for the average to be assigned to a variable named sum. The code follows that instruction, although in normal programming average would be a clearer variable name and sum is also the name of a Python built-in function.
3. Choose a suitable data type and explain
| Data value | Suitable type | Reason |
|---|---|---|
| a) Number of months in a year | int | Whole-number count (12). |
| b) Resident of Delhi or not | bool | Answer is True or False. |
| c) Mobile number | str | It is an identifier, not a quantity for arithmetic; string preserves leading zeroes and symbols. |
| d) Pocket money | float or int | May contain a fractional amount; depends on how it is recorded. |
| e) Volume of a sphere | float | Usually a calculated value with a fractional part. |
| f) Perimeter of a square | float or int | Depends on the side length and may be fractional. |
| g) Name of the student | str | A name is text. |
| h) Address of the student | str | An address is textual information. |
4. Find the output when num1 = 4, num2 = 3, num3 = 2
Assume the initial values are assigned before the statements. The statements are evaluated in order. The printed item (e) uses c, but no value for c is defined in the question; therefore it raises a NameError if the statements are run as one continuous program.
| Part | Statement | Result / explanation |
|---|---|---|
| a | num1 += num2 + num3 | num1 = 4 + 3 + 2 = 9 |
| b | print(num1) | 9 |
| c | num1 = num1 ** (num2 + num3) | 9 ** 5 = 59049 |
| d | print(num1) | 59049 |
| e | num1 **= num2 + c | NameError: name c is not defined. |
| f | num1 = '5' + '5' | num1 = '55' (string concatenation). |
| g | print(num1) | 55 (a string). |
| h | print(4.00/(2.0+2.0)) | 1.0 |
| i | num1 = 2+9*((3*12)-8)/10 | 25.4 |
| j | print(num1) | 25.4 |
| k | num1 = float(10) | 10.0 |
| l | print(num1) | 10.0 |
| m | num1 = int('3.14') | ValueError: '3.14' is not a valid integer literal. |
| n | print(num1) | Not reached in a continuous run because item (m) raises an error. If run separately after a successful assignment, it prints the current value. |
| o | print(10 != 9 and 20 >= 20) | True (both conditions are True). |
| p | print(5 % 10 + 10 < 50 and 29 <= 29) | True (15 < 50 and 29 <= 29). |
int("3.14") raises ValueError. To convert decimal text to an integer by truncating its fractional part, use int(float("3.14")), which gives 3.5. Categorise the errors
25 / 0– Runtime error (ZeroDivisionError).num1 = 25; num2 = 0; num1/num2– Runtime error (ZeroDivisionError).
6. Program to calculate amount payable using simple interest
Given: Principal = P, Rate = R% per annum, Time = T years.
Simple Interest: SI = (P × R × T) / 100. Amount payable = Principal + SI.
P = float(input("Enter principal amount: "))
R = float(input("Enter rate of interest: "))
T = float(input("Enter time in years: "))
SI = (P * R * T) / 100
amount_payable = P + SI
print("Simple Interest =", SI)
print("Amount Payable =", amount_payable)
7. Repeat “GOOD MORNING” n times
n = int(input("Enter number of repetitions: "))
for i in range(n):
print("GOOD MORNING")
8. Program to find the average of 3 numbers
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))
average = (num1 + num2 + num3) / 3
print("Average =", average)
9. Display the year in which the user will turn 100
from datetime import date
name = input("Enter your name: ")
age = int(input("Enter your age: "))
current_year = date.today().year
year_turn_100 = current_year + (100 - age)
print(name, "will turn 100 in the year", year_turn_100)This beginner-level solution estimates the year by adding the number of years remaining to age 100 to the current calendar year. It does not account for whether the user's birthday has already occurred in the current year.
10. Difference between else and elif
elif checks another condition when the preceding conditions are False. else does not have a condition; it executes as the default block when all preceding if/elif conditions are False.
11. Find the output of the program segments
(a)
for i in range(20, 30, 2):
print(i)Output:20
22
24
26
28
(b)
country = 'INDIA'
for i in country:
print(i)Output:I
N
D
I
A
(c)
i = 0
sum = 0
while i < 9:
if i % 4 == 0:
sum = sum + i
i = i + 2
print(sum)The values of i are 0, 2, 4, 6 and 8. The values divisible by 4 are 0, 4 and 8. Their sum is 12.
12
Case Study Based Question – Student Management Information System (SMIS)
Schools use a Student Management Information System (SMIS) to manage student-related data. The textbook lists these facilities:
- Recording and maintaining personal details of students.
- Maintaining marks scored in assessments and computing student results.
- Keeping track of student attendance.
- Managing other student-related data in the school.
The textbook asks learners to identify personal details from a school identity card and write a program to accept those details for all students and display them in the specified format. The sample identity-card layout on printed page 54 contains school name, student name, roll number, class, section, address lines, city, PIN code and parent/guardian contact number.
Example – Accept and display one student's details
school_name = input("Enter school name: ")
student_name = input("Enter student name: ")
roll_no = input("Enter roll number: ")
student_class = input("Enter class: ")
section = input("Enter section: ")
address1 = input("Enter address line 1: ")
address2 = input("Enter address line 2: ")
city = input("Enter city: ")
pin_code = input("Enter PIN code: ")
guardian_contact = input("Enter parent/guardian contact: ")
print("\\n", school_name)
print("Student Name:", student_name, " Roll No:", roll_no)
print("Class:", student_class, " Section:", section)
print("Address:", address1)
print(" ", address2)
print("City:", city, " Pin Code:", pin_code)
print("Parent/Guardian Contact No:", guardian_contact)
Possible extensions for practice
- Accept details for multiple students using a loop.
- Store each student's details in a dictionary.
- Accept subject marks and calculate total and average.
- Record attendance using values such as Present and Absent.
TEXTBOOK SOLUTION
Step-by-step solved textbook exercises, derivations, and solutions.
Exercise Solutions Being Updated
Step-by-step verified exercise solutions are currently being uploaded.
MCQ
High-yield board questions, previous year questions (PYQs), and model answer keys.
Important Questions Being Compiled
Board blueprint and previous years' exam questions for this chapter will be live soon.