Brief Overview of Python
Overview
This chapter introduces Python as an interpreted, high-level language and covers its building blocks: execution modes, identifiers, variables, data types, operators, expressions, input/output and type conversion. Students then learn to control the flow of a program with if, if-elif-else, while and for loops, and to recognise and fix syntax, runtime and logical errors.
Fully in the 2025-26 syllabus: execution modes, program structure, indentation, identifiers, keywords, constants, variables, operators and precedence, data types, mutable and immutable types, expressions, comments, input/output, type conversion, debugging, if-else, if-elif-else, while and for loops. The while loop and mutable/immutable types are in the syllabus though NCERT covers them only briefly; user-defined functions are not in the syllabus.
Learning outcomes
- Students will be able to run Python statements in interactive mode and write, save and run programs in script mode.
- Students will be able to identify keywords and frame valid identifiers and variables following Python's rules.
- Students will be able to name Python's data types and classify them as mutable or immutable.
- Students will be able to use arithmetic, relational, logical, assignment, membership and identity operators and evaluate expressions using operator precedence.
- Students will be able to accept input, display formatted output and convert values between data types.
- Students will be able to distinguish syntax, logical and runtime errors and debug simple programs.
- Students will be able to write programs using if, if-else and if-elif-else statements.
- Students will be able to write programs using while loops, for loops with range(), and nested loops.
Lesson plan
Show IDLE in the lab. Students type small expressions at the >>> prompt (marks totals, cricket strike rate) and then save the same lines as a .py file and run it with F5. Board: table comparing the two modes.
Quick game: the teacher writes 15 names on the board and students vote valid/invalid with reasons. In the lab, students assign values, swap two variables and use type() and id().
Students guess the type of tricky literals ("45", 2.5e3, True). Demonstrate with id() that a list changes in place and a string does not. Discuss why strings cannot be edited with an index.
Board drill: evaluate 8 expressions step by step, including //, %, ** and logical operators. Students verify each in interactive mode. Pair activity: write the truth table for and, or, not.
Students write a 'bio-data' program using input() and print() with sep and end. Deliberately run age + 1 without int() and read the error message together.
Hand out a printed program with 6 planted errors. Students classify each as syntax, runtime or logical and correct it, then test in the lab.
Build the grade calculator and the discount program together. Discuss why the order of conditions matters by reversing the ladder and observing the wrong output.
Dry-run the digit-sum and reverse-number program on the board with a trace table, then code it. Show an infinite loop and how to stop it with Ctrl+C.
Students predict the values of 6 range() calls before checking with list(range(...)). Lab: multiplication table, sum of squares, and two star/number patterns.
Students complete the SI/CI, EMI, GST and vowel-count programs for the practical file. Class quiz with output-prediction and error-finding questions.
Notes
What is Python?
Python is a high-level, general-purpose programming language created by Guido van Rossum and first released in 1991. It is the language prescribed by CBSE for Informatics Practices because its code reads almost like English.
Key features to tell students:
- Interpreted: the Python interpreter reads and executes the program one statement at a time, so errors are reported as soon as they are reached.
- Free and open source, available for Windows, Linux and macOS.
- Case-sensitive:
Marks,marksandMARKSare three different names. - Uses indentation (spaces at the start of a line) to group statements, instead of braces.
- Has a huge standard library and extra libraries such as NumPy, Pandas and Matplotlib, which students will use in Class 12.
A program is an ordered set of instructions. The text of a program is called source code. The interpreter converts each line into a form the computer can execute.
print("Welcome to Informatics Practices")
print("Class XI, Session 2025-26")Welcome to Informatics Practices Class XI, Session 2025-26
Ask students why an interpreter is convenient for beginners: it stops at the first faulty line and shows the error immediately, so they can fix one mistake at a time.
Execution modes: interactive and script
Python code can be run in two ways.
1. Interactive mode (the Python shell). The prompt >>> waits for one statement. When you press Enter, the statement runs and the result appears on the next line. You do not even need print() to see the value of an expression. It is ideal for quick testing, but the statements are not saved.
2. Script mode. The program is typed in an editor (IDLE, Thonny, VS Code, etc.), saved with the extension .py, and run as a whole (in IDLE: Run > Run Module or F5; at the command line: python marks.py). The program can be saved, edited and run again. In script mode, values are shown only if you use print().
Below is an interactive-mode session. Notice that a bare expression shows its value, but an assignment shows nothing.
| Interactive mode | Script mode |
|---|---|
Runs one statement at a time at the >>> prompt | Runs a whole program saved in a .py file |
| Code is not saved | Code is saved and can be reused or edited |
| Value of an expression is shown automatically | Need print() to display any value |
| Best for testing small pieces of code | Best for complete programs and practical file work |
>>> 25 + 17
42
>>> runs = 48
>>> runs * 2
96
>>> runs
48
>>> "Virat " + "Kohli"
'Virat Kohli'Board questions often ask: "Differentiate between interactive mode and script mode" (2 marks). Two clear points of difference are enough.
Structure of a Python program and indentation
A typical Python program contains:
- Comments that explain the code (ignored by the interpreter).
- Import statements to use ready-made modules (for example
import math). - Statements: assignment, input/output, decision making and loops.
- Blocks: groups of statements that belong together, for example the statements inside an
ifor a loop.
Indentation means leaving spaces at the beginning of a line. In Python, indentation is compulsory: it tells the interpreter which statements form a block. A line ending with a colon : (after if, elif, else, for, while) must be followed by an indented block. All statements of one block must have the same indentation. The convention is 4 spaces per level.
# Program: check result of a student
marks = 72 # statement
if marks >= 33: # header line ends with a colon
print("Result: Pass") # indented block (4 spaces)
print("Well done!")
else:
print("Result: Fail")
print("Thank you") # not indented: runs in every caseResult: Pass Well done! Thank you
Missing or uneven indentation gives an IndentationError. For example, if the print after if marks >= 33: is not indented, Python reports: IndentationError: expected an indented block after 'if' statement on line 2. Ask students to use the Tab key in IDLE, which inserts 4 spaces.
Keywords
Keywords are reserved words that have a fixed meaning for the Python interpreter. They cannot be used as names of variables. Python 3 has 35 keywords; all are in lowercase except True, False and None. Because Python is case-sensitive, if is a keyword but If is not (though using it as a name would be confusing).
The list can be printed with the keyword module:
import keyword
print(keyword.kwlist)
print(len(keyword.kwlist), "keywords")['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield'] 35 keywords
Students need not memorise all 35. Make sure they recognise the common ones: if elif else for while in not and or is True False None break continue import def return del pass.
Identifiers and the rules for naming them
An identifier is a name given to a variable, function or other object in a program. Rules:
- It can contain letters (A-Z, a-z), digits (0-9) and the underscore
_. - It cannot start with a digit.
- It cannot be a keyword.
- No special symbols such as
@ # $ % ! -or spaces are allowed. - It is case-sensitive:
totalandTotalare different. - It can be of any length.
Good practice: use meaningful names such as total_marks or avgRuns instead of a or x1.
| Identifier | Valid? | Reason |
|---|---|---|
roll_no | Valid | Letters and underscore |
_count | Valid | May start with an underscore |
class12 | Valid | Digit is allowed after the first character |
12class | Invalid | Starts with a digit |
total marks | Invalid | Contains a space |
gst% | Invalid | Contains the special symbol % |
while | Invalid | It is a keyword |
While | Valid | Case differs from the keyword while (but avoid it) |
A favourite 1-mark question: "Which of the following is not a valid identifier?" Train students to check four things in order: first character, special symbols or spaces, keyword, case.
Variables, constants and assignment
A variable is a name that refers to a value stored in memory. In Python a variable is created the moment a value is assigned to it with =; there is no separate declaration. The same variable can later refer to a value of a different type.
Useful forms of assignment:
- Simple:
price = 250 - Multiple values in one line:
a, b, c = 10, 20, 30 - Same value to many:
x = y = z = 0 - Swapping without a third variable:
a, b = b, a
A variable must be assigned before it is used, otherwise Python raises a NameError.
A constant is a value that does not change. Fixed values written directly in code, such as 100, 3.14 or "Delhi", are called literals. Python has no special keyword for constants; by convention a name written in CAPITALS (for example PI = 3.14159 or GST_RATE = 18) signals that its value should not be changed.
PI = 3.14159 # constant by convention
radius = 7
area = PI * radius * radius
print("Area:", area)
a, b = 15, 40
a, b = b, a # swap
print("a =", a, "b =", b)
x = y = z = 0
print(x, y, z)
city = "Jaipur" # same name can later hold another type
print(type(radius), type(city))Area: 153.93791 a = 40 b = 15 0 0 0 <class 'int'> <class 'str'>
Every value in Python is an object with an identity (id()), a type (type()) and a value. Use id() when you teach mutable and immutable types.
Data types
The data type of a value decides what kind of value it is and which operations can be done on it. Use type() to find it.
- Numbers:
int(whole numbers of any size),float(numbers with a decimal point or in exponent form such as2.5e3),complex(for example3+4j). - Boolean (
bool): only two values,TrueandFalse. InternallyTruebehaves like 1 andFalselike 0. - Sequences:
str(text in single, double or triple quotes),list(items in[ ], changeable) andtuple(items in( ), not changeable). - Mapping:
dict(key-value pairs in{ }), covered in detail in the next chapter. - None: the special value
None(typeNoneType) means "no value".
A set (unordered collection of unique items) also exists; it is not in the IP syllabus.
values = [45, 99.5, 2+3j, True, "Kolkata", [1, 2], (5, 6), {"roll": 1}, None]
for v in values:
print(repr(v), "->", type(v))45 -> <class 'int'>
99.5 -> <class 'float'>
(2+3j) -> <class 'complex'>
True -> <class 'bool'>
'Kolkata' -> <class 'str'>
[1, 2] -> <class 'list'>
(5, 6) -> <class 'tuple'>
{'roll': 1} -> <class 'dict'>
None -> <class 'NoneType'>2.5e3 is a float (2500.0) even though it looks like a whole number, and "45" is a string, not an int. These are popular traps in MCQs.
Mutable and immutable data types
- Mutable types can be changed in place after creation:
list,dict(andset). - Immutable types cannot be changed in place:
int,float,complex,bool,str,tuple.
When we "change" an immutable value, for example city = city + " NCR", Python actually creates a new object and the variable starts referring to it. The identity (id()) of the variable therefore changes. When a list is changed, the same object is modified and its id() stays the same. Trying to change one character of a string gives a TypeError.
| Immutable | Mutable |
|---|---|
| int, float, complex, bool | list |
| str | dict |
| tuple | set (not in syllabus) |
marks = [80, 75, 90]
old_id = id(marks)
marks[1] = 78 # change in place
print(marks, "same object:", id(marks) == old_id)
city = "Delhi"
old_id = id(city)
city = city + " NCR" # new string object is created
print(city, "same object:", id(city) == old_id)
name = "ravi"
name[0] = "R" # strings are immutable[80, 78, 90] same object: True Delhi NCR same object: False TypeError: 'str' object does not support item assignment
Only immutable values can be dictionary keys. That is why a list cannot be used as a key; this links directly to Chapter 4.
Arithmetic operators
Operators are symbols that perform operations on values called operands. Arithmetic operators work on numbers; + and * also work on strings and lists.
Points to stress:
/always gives a float, even when the division is exact (10 / 2is5.0).//(floor division) gives the quotient rounded down towards minus infinity, so-17 // 4is-5, not-4.%gives the remainder; its sign follows the divisor, so-17 % 4is3.**is power:2 ** 10is1024."Ha" * 3gives"HaHaHa"(repetition) and"Raj" + "kot"gives"Rajkot"(concatenation).
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | Addition / concatenation | 17 + 4 | 21 |
- | Subtraction | 17 - 4 | 13 |
* | Multiplication / repetition | 17 * 4 | 68 |
/ | Division (float result) | 17 / 4 | 4.25 |
// | Floor division | 17 // 4 | 4 |
% | Modulus (remainder) | 17 % 4 | 1 |
** | Exponent | 2 ** 5 | 32 |
print(17 + 4, 17 - 4, 17 * 4, 17 / 4)
print(17 // 4, 17 % 4, 2 ** 5)
print(10 / 2, -17 // 4, -17 % 4, 17.0 // 4)
print("Ha" * 3, "Raj" + "kot")21 13 68 4.25 4 1 32 5.0 -5 3 4.0 HaHaHa Rajkot
Use % to teach two classic tricks: n % 2 == 0 tests for even numbers, and n % 10 gives the last digit of a number.
Relational, assignment and logical operators
Relational (comparison) operators compare two values and give True or False: ==, !=, >, <, >=, <=. Strings are compared letter by letter using their character codes, so "Apple" < "apple" is True (capital letters come first). Python allows chained comparisons such as 0 <= marks <= 100.
Assignment operators store a value. Augmented forms combine an operation with assignment: x += 5 means x = x + 5. Others: -=, *=, /=, //=, %=, **=.
Logical operators combine conditions:
and: True only if both sides are True.or: True if at least one side is True.not: reverses the truth value.
Python evaluates and/or from left to right and stops as soon as the answer is known (short-circuit evaluation). Values such as 0, 0.0, "", [], {} and None are treated as False; everything else is treated as True.
| A | B | A and B | A or B | not A |
|---|---|---|---|---|
| True | True | True | True | False |
| True | False | False | True | False |
| False | True | False | True | True |
| False | False | False | False | True |
marks, attendance = 68, 72
print(marks >= 33, marks == 100, "Apple" < "apple", 0 <= marks <= 100)
print(marks >= 33 and attendance >= 75)
print(marks >= 33 or attendance >= 75)
print(not attendance >= 75)
total = 100
total += 25
total //= 2
print(total)
print(bool(0), bool(""), bool("0"), bool([]))True False True True False True True 62 False False True False
Remind students that = assigns and == compares. Writing if marks = 33: is a syntax error.
Membership and identity operators
Membership operators check whether a value is present in a sequence (string, list, tuple) or among the keys of a dictionary:
ingives True if the value is found.not ingives True if the value is not found.
Identity operators check whether two names refer to the same object in memory:
isgives True if both refer to the same object.is notgives True if they refer to different objects.
== compares values, while is compares identity. Two different lists can have equal values but still be different objects. Use is mainly with None, for example if result is None:.
vowels = "aeiou"
print("e" in vowels, "z" not in vowels)
teams = ["CSK", "MI", "RCB"]
print("MI" in teams, "KKR" in teams)
list1 = [1, 2, 3]
list2 = [1, 2, 3]
list3 = list1
print(list1 == list2, list1 is list2, list1 is list3)True True True False True False True
The type matters with in: 5 in ["5", "6"] is False because the list holds strings, not numbers.
Precedence and associativity of operators
When an expression has several operators, precedence decides which is applied first. Operators on the same level are applied left to right (left associativity), except **, which is applied right to left. Parentheses ( ) override everything.
Worked example: evaluate 12 + 3 * 4 ** 2 // 5 - 1
4 ** 2= 16 →12 + 3 * 16 // 5 - 13 * 16= 48 (left to right among*and//) →12 + 48 // 5 - 148 // 5= 9 →12 + 9 - 112 + 9= 21, then21 - 1= 20
Note two surprises: -3 ** 2 is -9 because ** binds tighter than the unary minus, and 2 ** 3 ** 2 is 2 ** 9 = 512 because ** is right-associative.
| Level (high to low) | Operators | Description |
|---|---|---|
| 1 | ( ) | Parentheses |
| 2 | ** | Exponent (right to left) |
| 3 | +x, -x | Unary plus, unary minus |
| 4 | *, /, //, % | Multiply, divide, floor divide, modulus |
| 5 | +, - | Addition, subtraction |
| 6 | ==, !=, >, <, >=, <=, is, is not, in, not in | Comparison, identity, membership |
| 7 | not | Logical NOT |
| 8 | and | Logical AND |
| 9 | or | Logical OR |
| 10 | =, +=, -=, *=, /=, //=, %=, **= | Assignment (lowest) |
print(12 + 3 * 4 ** 2 // 5 - 1)
print(2 ** 3 ** 2, (2 ** 3) ** 2)
print(-3 ** 2, (-3) ** 2)
print(20 - 8 - 4, 30 / 5 * 3)
print(not 5 > 3 or 2 < 1)
print(10 > 5 and 3 > 4 or 7 > 2)20 512 64 -9 9 8 18.0 False True
The NCERT table lists relational operators on two sub-levels; in Python all comparison, identity and membership operators actually share one level and can be chained. When in doubt in an answer, add parentheses and show each step on a new line, which earns step marks.
Statements, expressions and their evaluation
An expression is a combination of values, variables and operators that evaluates to a single value, for example marks * 2, "Ram" + "pur" or price > 500. A single value or variable is also an expression; an operator alone is not.
A statement is a complete instruction that Python executes, such as an assignment (total = a + b), a print() call, an if statement or a loop. A statement may contain expressions.
While evaluating mixed expressions, Python converts the narrower type to the wider one: int → float → complex. So 7 + 2.0 gives 9.0, and any expression containing / gives a float.
a, b = 15, 4
print(a / b + (a % b) * 2) # 3.75 + 3*2
print(a // b + 2.0) # int + float -> float
print(15.0 / 4.0 + (8 + 3.0))
print(a > b and a % b == 3)9.75 5.0 14.75 True
For "evaluate the expression" questions, write each step on a separate line and clearly mark the final answer and its type (for example 9.0, not 9).
Comments
A comment is text in a program that the interpreter ignores. Comments explain the purpose of the code to anyone reading it, including the programmer later on.
- A single-line comment starts with
#. Everything after#on that line is ignored. It can be on its own line or at the end of a statement (inline comment). - For a longer note across several lines, either start each line with
#, or enclose the text in triple quotes ('''...'''or"""..."""). A triple-quoted string that is not assigned to anything is simply ignored, so it works like a multi-line comment. At the top of a program or function it is called a docstring.
"""
Program : Electricity bill
Author : Class XI-B
"""
units = 150 # units consumed this month
rate = 6.5 # rupees per unit
# bill is units multiplied by rate
print("Bill amount: Rs", units * rate)Bill amount: Rs 975.0
Insist that every practical-file program begins with a comment block giving the aim of the program. It is good habit and examiners notice it.
Input and output statements
input(prompt) shows the prompt, waits for the user to type something and press Enter, and always returns a string. To use the value as a number, convert it: int(input(...)) or float(input(...)).
print() displays values on the screen. Its useful options:
- Several values separated by commas are printed with one space between them.
sep=sets the separator between values (default is a space).end=sets what is printed at the end (default is a newline\n).
In the sample run below, the values typed by the user are shown after each prompt.
name = input("Enter your name: ")
age = int(input("Enter your age: "))
print("Hello", name)
print("Next year you will be", age + 1)
print(28, 10, 2026, sep="/")
print("Loading", end="...")
print("done")Enter your name: Meera Enter your age: 16 Hello Meera Next year you will be 17 28/10/2026 Loading...done
If int() is forgotten, age + 1 raises TypeError: can only concatenate str (not "int") to str. This is the most common error in early lab sessions.
Data type conversion
Converting a value from one type to another is called type conversion (type casting).
Implicit conversion is done automatically by Python when it is safe, for example int + float gives a float, and True + 3 gives 4.
Explicit conversion is done by the programmer using functions:
int(x): converts to integer. A float is truncated (decimal part dropped, not rounded):int(9.99)is9. A string must look like a whole number:int("45")works, butint("12.5")andint("abc")give aValueError.float(x):float("3.5")is3.5,float(7)is7.0.str(x):str(100)is"100", useful when joining numbers with text.bool(x): False for 0, empty string or empty collection, otherwise True.round(x, n)rounds a number tondecimal places (useful for money).
print(5 + 2.5, True + 3) # implicit
print(int("45") + 5, int(9.99), int(-9.99))
print(float("3.5") * 2, float(7))
print("Score: " + str(100) + "%")
print(round(1234.5678, 2), round(7.5))
print(int("12.5"))7.5 4 50 9 -9 7.0 7.0 Score: 100% 1234.57 8 ValueError: invalid literal for int() with base 10: '12.5'
round(7.5) gives 8 but round(6.5) gives 6 because Python rounds exact halves to the nearest even number. Avoid asking students to predict round() of exact halves.
Debugging: syntax, logical and runtime errors
Finding and removing errors (bugs) from a program is called debugging. Errors are of three kinds:
- Syntax error: the code breaks the grammar rules of Python, for example a missing colon, unmatched brackets or quotes, or a misspelt keyword. The program does not run at all; Python points to the line. Example: leaving out the colon in
if marks >= 33givesSyntaxError: expected ':'(older Python versions simply sayinvalid syntax).
- Logical error: the program runs without any message but gives a wrong result because the logic is wrong. Python cannot detect it. Example:
avg = a + b / 2instead ofavg = (a + b) / 2. Found by testing with known answers.
- Runtime error (exception): the syntax is correct and the program starts, but it stops abruptly while running because an operation is impossible, such as division by zero, using an undefined variable, or converting
"abc"to int.
Common runtime errors: ZeroDivisionError, NameError, TypeError, ValueError, IndexError, KeyError.
| Error | When it is found | Example | Message |
|---|---|---|---|
| Syntax | Before the program runs | print("Hi" | SyntaxError |
| Runtime | While the program runs | 10 / 0 | ZeroDivisionError: division by zero |
| Runtime | While the program runs | print(total) when total was never assigned | NameError: name 'total' is not defined |
| Runtime | While the program runs | "5" + 5 | TypeError |
| Logical | Only by checking the output | avg = a + b / 2 | No message; wrong answer |
a, b = 60, 80
avg = a + b / 2 # logical error: runs, but wrong
print("Wrong average:", avg)
avg = (a + b) / 2 # corrected
print("Correct average:", avg)
students = 0
print("Per student:", 500 / students) # runtime errorWrong average: 100.0 Correct average: 70.0 ZeroDivisionError: division by zero
In "find the errors and rewrite the code" questions (very common in CBSE papers), students should underline each correction. Typical planted errors: missing colon, = instead of ==, wrong case (Print, If), missing quotes, wrong indentation, input() value used without int().
Built-in functions and modules
A function is a named group of statements that performs a task. Python provides many built-in functions that are always available, for example print(), input(), int(), float(), str(), type(), len(), abs(), round(), max(), min() and id(). A function may take arguments (values in the brackets) and may return a value.
A module is a Python file containing related functions. It is used after an import statement. The math module is handy in practicals: math.sqrt(), math.pow(), math.ceil(), math.floor() and the constant math.pi.
import math
print(abs(-25), max(12, 45, 7), min(12, 45, 7))
print(math.sqrt(144), math.ceil(4.1), math.floor(4.9))
print(round(math.pi * 7 * 7, 2))25 45 7 12.0 5 4 153.94
User-defined functions with def are not part of the Class XI IP syllabus. Students only need to use built-in functions and simple modules.
Decision making: if, if-else and if-elif-else
By default statements run one after another (sequential flow). A selection (decision-making) statement chooses which block to run based on a condition.
if: runs the block only when the condition is True.if-else: runs one block when the condition is True and another when it is False.if-elif-else: checks several conditions in order and runs the block of the first True condition;else(optional) runs if none is True. Only one block is executed.
Conditions in an elif ladder should be arranged carefully: once a condition is True, the rest are skipped.
An if can also be placed inside another if (nested if).
percent = 78.5
if percent >= 90:
grade = "A1"
elif percent >= 75:
grade = "A2"
elif percent >= 60:
grade = "B"
elif percent >= 33:
grade = "C"
else:
grade = "Fail"
print("Grade:", grade)
age = 17
if age >= 18:
print("Eligible to vote")
else:
print("Wait", 18 - age, "year(s) to vote")Grade: A2 Wait 1 year(s) to vote
Ask students what happens if the conditions are written in the reverse order (percent >= 33 first). Every passing student would get grade C: a good example of a logical error.
The while loop
Iteration (looping) means repeating a block of statements. A while loop repeats its block as long as its condition is True. The condition is checked before every repetition.
Three parts of a correct while loop:
- Initialise the control variable before the loop.
- Test the condition in the
whileline. - Update the control variable inside the loop.
If the update is forgotten, the condition never becomes False and the loop runs forever (infinite loop); press Ctrl+C to stop it. while is useful when the number of repetitions is not known in advance, for example processing the digits of a number.
count = 1 # initialise
while count <= 5: # test
print(count, end=" ")
count += 1 # update
print()
num = 4725
digit_sum = 0
reverse = 0
while num > 0:
digit = num % 10
digit_sum += digit
reverse = reverse * 10 + digit
num //= 10
print("Sum of digits:", digit_sum, "Reverse:", reverse)1 2 3 4 5 Sum of digits: 18 Reverse: 5274
A dry run table (columns: num, digit, digit_sum, reverse) on the board makes the digit loop easy to follow. Output-prediction questions on while loops are common.
The for loop and range()
A for loop repeats its block once for each item in a sequence (string, list, tuple, dictionary or range). The loop variable takes each item in turn.
range() generates a sequence of integers:
range(stop): 0, 1, ..., stop-1range(start, stop): start, start+1, ..., stop-1range(start, stop, step): start, start+step, ...; a negative step counts down.
The stop value is never included. start, stop and step must be integers and step cannot be 0.
Use for when the number of repetitions is known in advance; use while when it depends on a condition.
| Call | Values produced |
|---|---|
range(5) | 0 1 2 3 4 |
range(2, 7) | 2 3 4 5 6 |
range(1, 10, 3) | 1 4 7 |
range(10, 0, -2) | 10 8 6 4 2 |
range(5, 1) | (empty) |
for ch in "INDIA":
print(ch, end=" ")
print()
for n in range(10, 0, -2):
print(n, end=" ")
print()
print(list(range(1, 10, 3)), list(range(5, 1)))
total = 0
for i in range(1, 11):
total += i
print("Sum of 1 to 10 =", total)I N D I A 10 8 6 4 2 [1, 4, 7] [] Sum of 1 to 10 = 55
Quick check for students: the number of values in range(a, b) is b - a. So range(1, 11) gives 10 values.
Nested loops
A loop placed inside another loop is a nested loop. For each single repetition of the outer loop, the inner loop runs completely. If the outer loop runs 3 times and the inner loop 4 times, the inner body runs 3 × 4 = 12 times.
Nested loops are used for patterns, tables and working with rows and columns.
for row in range(1, 5):
for col in range(1, row + 1):
print(col, end=" ")
print() # new line after each row
for i in range(2, 4):
for j in range(1, 4):
print(i, "x", j, "=", i * j, end=" ")
print()1 1 2 1 2 3 1 2 3 4 2 x 1 = 2 2 x 2 = 4 2 x 3 = 6 3 x 1 = 3 3 x 2 = 6 3 x 3 = 9
For pattern questions, first find the relation between the row number and how many items are printed in that row; the inner range() follows from that.
break and continue (Enrichment)
These two statements are not named in the syllabus but appear in many practical programs.
breakends the loop immediately; control goes to the first statement after the loop.continueskips the rest of the current repetition and goes to the next one.
for n in range(1, 11):
if n % 3 == 0:
continue # skip multiples of 3
if n > 8:
break # stop the loop
print(n, end=" ")1 2 4 5 7 8
Key terms
- Interpreter
- Software that translates and executes a program one statement at a time.
- Interactive mode
- Running Python statements one at a time at the >>> prompt; code is not saved.
- Script mode
- Writing a program in a .py file, saving it and running it as a whole.
- Keyword
- A reserved word with a special meaning that cannot be used as an identifier.
- Identifier
- A name given to a variable, function or other object in a program.
- Variable
- A name that refers to a value stored in memory.
- Literal
- A fixed value written directly in code, such as 25, 3.5 or "Pune".
- Constant
- A value that does not change during the program; by convention written in capitals.
- Data type
- The kind of value (int, float, str, list, etc.) that decides which operations are allowed.
- Mutable
- A type whose value can be changed in place, such as list and dict.
- Immutable
- A type whose value cannot be changed in place, such as int, float, str and tuple.
- Operator
- A symbol that performs an operation on one or more operands.
- Precedence
- The order in which operators in an expression are applied.
- Expression
- A combination of values, variables and operators that evaluates to a single value.
- Statement
- A complete instruction that the interpreter can execute.
- Indentation
- Spaces at the start of a line that mark a block of code in Python.
- Comment
- Text after # (or in an unassigned triple-quoted string) that the interpreter ignores.
- Type conversion
- Changing a value from one data type to another, implicitly or explicitly.
- Debugging
- The process of finding and removing errors from a program.
- Infinite loop
- A loop whose condition never becomes False, so it never ends.
MCQs
Tap an option to check it, or use Show answers above to reveal them all.
-
Which of the following is a valid identifier in Python?
Answer(c) _roll_no
An identifier may start with an underscore.
2nd_termstarts with a digit,total-markshas a hyphen andforis a keyword. -
In which mode does Python display the value of an expression without using
print()?Answer(a) Interactive mode
At the
>>>prompt the value of a bare expression is echoed automatically. In script mode,print()is needed. -
Which of these is not a keyword in Python?
Answer(c) print
printis a built-in function, not a keyword.None,elifandpassare keywords. -
What is the output of the following code?
Python print(23 // 4, 23 % 4)Answer(c) 5 3
23 // 4gives the quotient 5 and23 % 4gives the remainder 3. -
What is the output of the following code?
Python print(2 ** 3 ** 2)Answer(d) 512
**is right-associative:2 ** 3 ** 2is2 ** 9= 512. -
Which data type is mutable?
Answer(b) list
Lists can be changed in place; the other three are immutable.
-
What will
type(5 / 5)return?Python print(type(5 / 5))Answer(d)
<class 'float'>The
/operator always returns a float, even when the division is exact (1.0). -
What is the output of the following code?
Python print(-4 ** 2)Answer(b) -16
**has higher precedence than unary minus, so it is-(4 ** 2)= -16. -
What does
int("7.9")produce?Answer(d) ValueError
int()cannot convert a string that contains a decimal point.int(7.9)(a float, without quotes) would give 7. -
What is the output of the following code?
Python a, b = 10, 20 print(a < b and b < a or a == b)Answer(c) False
andis applied beforeor:(True and False) or False=False or False= False. -
Which error occurs when a program divides a number by zero?
Answer(a) ZeroDivisionError
Division by zero is detected only while running, so it is a runtime error named
ZeroDivisionError. -
A program to find the average of three numbers runs without any message but prints a wrong answer. This is a:
Answer(c) Logical error
The program runs fully but the logic (formula) is wrong, which is a logical error.
-
What is the output of the following code?
Python for i in range(2, 10, 2): print(i, end=" ")Answer(d) 2 4 6 8
range(2, 10, 2)produces 2, 4, 6, 8; the stop value 10 is excluded. -
How many times will the following loop run?
Python x = 20 count = 0 while x > 0: x -= 5 count += 1 print(count)Answer(a) 4
x takes the values 20, 15, 10, 5. When x becomes 0 the condition fails, so the body runs 4 times.
-
Which symbol is used to write a single-line comment in Python?
Answer(b) #
Everything after
#on a line is a comment. -
What is the output of the following code?
Python m = 65 if m >= 75: print("Merit") elif m >= 33: print("Pass") else: print("Fail")Answer(a) Pass
65 >= 75 is False, so Python checks the
elif: 65 >= 33 is True, so "Pass" is printed and the rest of the ladder is skipped. -
What is the output of
print("5" * 3)?Python print("5" * 3)Answer(a) 555
*with a string and an integer repeats the string. -
Which statement about
input()is correct?Answer(b) It always returns a string
input()returns whatever is typed as a string; it must be converted withint()orfloat()for calculations. -
What is the output of the following code?
Python p = [1, 2] q = [1, 2] print(p == q, p is q)Answer(d) True False
==compares values (equal), whileischecks whether both names refer to the same object (they are two different lists). -
Which of the following is evaluated first in
8 + 6 / 3 * 2 - 1?Answer(b) 6 / 3
/and*share a level higher than+and-, and they are applied left to right, so6 / 3is done first. The value is 11.0.
Assertion–Reason
Assertion (A): In Python,
10 / 5gives the value2.0.Reason (R): The
/operator always returns a floating-point result.Answer(A)
Both are true and R explains why the result is 2.0 and not 2.
Assertion (A): A string can be used where Python expects an immutable value.
Reason (R): After a string is created, its individual characters can be changed using an index.
Answer(C)
Strings are immutable, so A is true. R is false:
s[0] = "x"raises aTypeError.Assertion (A):
total_2025is a valid identifier.Reason (R): An identifier can contain digits, but it cannot begin with one.
Answer(A)
Both are true and R is the rule that makes
total_2025valid (it begins with a letter).Assertion (A):
range(1, 5)produces the numbers 1, 2, 3, 4 and 5.Reason (R): The stop value given to
range()is excluded.Answer(D)
A is false: 5 is not produced. R is true and is the reason why.
Assertion (A): A logical error does not stop the execution of a program.
Reason (R): Python detects logical errors before running the program.
Answer(C)
A is true: the program runs and gives a wrong result. R is false: Python cannot detect logical errors at all.
Short answer
- 2 marks
Differentiate between interactive mode and script mode of Python. (Any two points)
Answer- In interactive mode, statements are typed at the
>>>prompt and executed one at a time; in script mode, a complete program is written in a file and run together. - Interactive-mode code is not saved, whereas a script is saved with a
.pyextension and can be reused. - Interactive mode shows the value of an expression automatically; script mode needs
print().
- In interactive mode, statements are typed at the
- 2 marks
Identify the valid and invalid identifiers, giving a reason for each invalid one:
Sales2026,net pay,_tax,import,3rdRank,rate%AnswerValid:
Sales2026,_tax.Invalid:
net pay(contains a space),import(keyword),3rdRank(starts with a digit),rate%(contains the special symbol %). - 2 marks
What are mutable and immutable data types? Give two examples of each.
AnswerA mutable data type allows its value to be changed in place after creation, for example
listanddict.An immutable data type does not allow its value to be changed in place; any change creates a new object. Examples:
int,float,str,tuple. - 2 marks
Evaluate the following expressions, showing the steps:
(a)
30 - 4 * 3 ** 2 // 5(b)
not 15 > 10 and 7 % 2 == 1Answer(a)
3 ** 2= 9 →4 * 9= 36 →36 // 5= 7 →30 - 7= 23(b)
15 > 10is True and7 % 2 == 1is True.not True= False;False and True= FalsePython print(30 - 4 * 3 ** 2 // 5) print(not 15 > 10 and 7 % 2 == 1)Output23 False
- 2 marks
Predict the output of the following code.
Python s = 0 for i in range(1, 10, 2): s = s + i print(s, end=" ") print("|", s)AnswerThe loop runs for i = 1, 3, 5, 7, 9 and adds them to s. Inside the loop only the running total is printed on one line.
Python s = 0 for i in range(1, 10, 2): s = s + i print(s, end=" ") print("|", s)Output1 4 9 16 25 | 25
- 2 marks
Rewrite the following code after removing the errors. Underline each correction.
Python num = Int(input("Enter a number: ") If num % 2 = 0 print("Even") else Print("Odd")AnswerCorrections:
Int→int(case), add closing bracket on line 1,If→if,=→==, colon after the condition,elseneeds a colon, andPrint→print. The corrected code is:Python num = int(input("Enter a number: ")) if num % 2 == 0: print("Even") else: print("Odd")OutputEnter a number: 14 Even
- 2 marks
Name the type of error in each case: (a) a closing quote is missing in a
print()statement; (b) the program tries to use a variable that was never assigned; (c) area of a rectangle is calculated as2 * (l + b); (d)int("twenty").Answer(a) Syntax error
(b) Runtime error (
NameError)(c) Logical error (that is the perimeter formula)
(d) Runtime error (
ValueError) - 2 marks
What is the difference between
=and==? Give an example of each.Answer=is the assignment operator; it stores a value in a variable, e.g.marks = 90.==is a relational operator; it compares two values and returns True or False, e.g.marks == 90gives True when marks is 90. - 2 marks
Write the output of the following code.
Python for r in range(1, 4): for c in range(r): print("*", end="") print()AnswerThe outer loop runs 3 times; for row r the inner loop prints
*r times.Python for r in range(1, 4): for c in range(r): print("*", end="") print()Output* ** ***
- 2 marks
What is type conversion? Differentiate between implicit and explicit conversion with an example each.
AnswerChanging a value from one data type to another is type conversion.
Implicit: done automatically by Python, e.g.
5 + 2.5gives7.5(int converted to float).Explicit: done by the programmer with a function, e.g.
int("25") + 5gives30. - 2 marks
Convert the following
forloop into an equivalentwhileloop.Python for k in range(20, 4, -5): print(k)AnswerThe control variable is initialised before the loop, tested in the
whileline and decreased inside the body:Python k = 20 while k > 4: print(k) k = k - 5Output20 15 10 5
- 2 marks
What is the role of indentation in Python? What happens if a statement inside an
ifblock is not indented?AnswerIndentation (leading spaces) marks which statements belong to a block, such as the body of an
if,elseor a loop. All statements of a block must have the same indentation. If the statement afterif ...:is not indented, Python raises anIndentationErrorand the program does not run.
Long answer
- 3 marks
Explain any three types of operators in Python with two examples each. (3 marks)
Answer- Arithmetic operators perform calculations:
17 // 5gives 3,2 ** 4gives 16. - Relational operators compare values and give True/False:
45 > 30gives True,"abc" == "ABC"gives False. - Logical operators combine conditions:
marks >= 33 and attendance >= 75;not (age < 18).
(Membership
in/not inand identityis/is notmay also be explained.) - Arithmetic operators perform calculations:
- 3 marks
What is debugging? Explain the three types of errors with one example each. (3 marks)
AnswerDebugging is finding and removing errors from a program.
- Syntax error: breaks the rules of the language; the program does not run. Example:
while x < 5(colon missing). - Runtime error: occurs during execution and stops the program abruptly. Example:
print(100 / 0)givesZeroDivisionError. - Logical error: the program runs but gives a wrong output because of wrong logic. Example:
avg = a + b / 2instead of(a + b) / 2.
- Syntax error: breaks the rules of the language; the program does not run. Example:
- 3 marks
Write a program to input the cost price and selling price of an item and print whether there is a profit or a loss, and of how much. Also print the profit or loss percentage. (3 marks)
AnswerProgram with a sample run:
Python cp = float(input("Enter cost price: ")) sp = float(input("Enter selling price: ")) if sp > cp: profit = sp - cp print("Profit of Rs", profit) print("Profit % =", round(profit / cp * 100, 2)) elif cp > sp: loss = cp - sp print("Loss of Rs", loss) print("Loss % =", round(loss / cp * 100, 2)) else: print("No profit, no loss")OutputEnter cost price: 1250 Enter selling price: 1400 Profit of Rs 150.0 Profit % = 12.0
- 3 marks
Write a program that reads a number and prints its multiplication table up to 10 in the format
7 x 1 = 7. Also print the sum of all the multiples. (3 marks)AnswerProgram with a sample run:
Python n = int(input("Enter a number: ")) total = 0 for i in range(1, 11): print(n, "x", i, "=", n * i) total += n * i print("Sum of multiples:", total)OutputEnter a number: 7 7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35 7 x 6 = 42 7 x 7 = 49 7 x 8 = 56 7 x 9 = 63 7 x 10 = 70 Sum of multiples: 385
- 5 marks
Write a program to input a positive integer and print: (a) the number of digits, (b) the sum of the digits, (c) whether it is a palindrome. Use a
whileloop. (5 marks)AnswerA copy of the number is kept so that it can be compared with the reverse at the end.
Python n = int(input("Enter a positive integer: ")) temp = n digits = 0 s = 0 rev = 0 while temp > 0: d = temp % 10 digits += 1 s += d rev = rev * 10 + d temp //= 10 print("Number of digits:", digits) print("Sum of digits:", s) if rev == n: print(n, "is a palindrome") else: print(n, "is not a palindrome")OutputEnter a positive integer: 12321 Number of digits: 5 Sum of digits: 9 12321 is a palindrome
- 5 marks
An electricity board charges as follows: first 100 units at Rs 4 per unit, next 100 units at Rs 6 per unit, and units above 200 at Rs 8 per unit. A fixed charge of Rs 50 is added to every bill. Write a program to input units consumed and print the bill. (5 marks)
AnswerThe slabs are handled with an if-elif-else ladder; each slab charges only the units that fall inside it.
Python units = int(input("Enter units consumed: ")) if units <= 100: charge = units * 4 elif units <= 200: charge = 100 * 4 + (units - 100) * 6 else: charge = 100 * 4 + 100 * 6 + (units - 200) * 8 bill = charge + 50 print("Energy charge: Rs", charge) print("Total bill: Rs", bill)OutputEnter units consumed: 265 Energy charge: Rs 1520 Total bill: Rs 1570
- 3 marks
Explain the
forloop and therange()function with its three forms. Write the output offor i in range(15, 2, -4): print(i, end=" "). (3 marks)AnswerA
forloop repeats its body once for each item of a sequence.range()creates a sequence of integers:range(stop)from 0 to stop-1;range(start, stop)from start to stop-1;range(start, stop, step)in jumps of step (negative step counts down). The stop value is never included.For the given loop the values are 15, 11, 7, 3:
Python for i in range(15, 2, -4): print(i, end=" ")Output15 11 7 3
- 3 marks
Write a program to print the following pattern for n rows (n is input by the user). Sample for n = 4:
12 23 3 34 4 4 4(3 marks)
AnswerRow i prints the number i, i times, using a nested loop:
Python n = int(input("Enter number of rows: ")) for i in range(1, n + 1): for j in range(i): print(i, end=" ") print()OutputEnter number of rows: 4 1 2 2 3 3 3 4 4 4 4
Case-based
Ritika is writing a program for her school canteen. Each item has a price, and GST of 5% is added to the bill. Her first draft is shown below, but it gives an error when run.
price = input("Enter price: ")
qty = int(input("Enter quantity: "))
amount = price * qty
gst = amount * 5 / 100
print("Total:", amount + gst)Enter price: 40 Enter quantity: 3 TypeError: unsupported operand type(s) for /: 'str' and 'int'
- 1 mark
Why does the program stop with a
TypeError?Answerpriceis a string becauseinput()returns a string. Soprice * qtyrepeats the text ("404040"),amount * 5repeats it again, and then dividing a string by 100 is not allowed, so line 4 fails. - 1 mark
Rewrite line 1 so that the program works for prices such as 42.50.
Answerprice = float(input("Enter price: ")) - 1 mark
Name the type of error and say when it is detected.
AnswerIt is a runtime error (
TypeError); it is detected while the program is running, when line 4 is executed. - 1 mark
Write the output of the corrected program for price 40 and quantity 3.
AnswerPython price = float(input("Enter price: ")) qty = int(input("Enter quantity: ")) amount = price * qty gst = amount * 5 / 100 print("Total:", amount + gst)OutputEnter price: 40 Enter quantity: 3 Total: 126.0
A cricket coach records the runs scored by a batter in an over: 4, 0, 6, 1, 1, 4. He wants a program that uses a loop to find the total runs, the number of boundaries (4s and 6s) and the number of dot balls (0 runs).
- 1 mark
Which loop is more suitable here,
fororwhile? Why?AnswerA
forloop, because the number of balls (items) is known in advance and we simply visit each item. - 1 mark
Which operator would you use to check whether a score is a boundary? Write the condition.
AnswerThe membership operator
in:if run in (4, 6):(orrun == 4 or run == 6). - 2 marks
Write the complete program and its output.
AnswerPython over = [4, 0, 6, 1, 1, 4] total = boundaries = dots = 0 for run in over: total += run if run in (4, 6): boundaries += 1 elif run == 0: dots += 1 print("Total runs:", total) print("Boundaries:", boundaries) print("Dot balls:", dots)OutputTotal runs: 16 Boundaries: 3 Dot balls: 1
Aman typed the following statements in Python's interactive mode to explore operators.
>>> a = 17
>>> b = 5
>>> a // b
3
>>> a % b
2
>>> a / b
3.4
>>> a ** 2 > 250 and b != 5
False- 1 mark
Why was no output shown after
a = 17?AnswerIt is an assignment statement, not an expression; assignments do not produce a value to display.
- 1 mark
Which result has the data type
float, and why?Answera / bgives3.4, a float, because the/operator always returns a float. - 1 mark
Explain why the last statement gives
False.Answera ** 2 > 250is289 > 250, which is True;b != 5is False.True and Falseis False.
Practicals
1Average and grade
Write a program to input the marks (out of 100) of a student in five subjects and display the total, the average and the grade using this table: average 90 and above A1, 75 to below 90 A2, 60 to below 75 B, 33 to below 60 C, below 33 Fail.
total = 0
for i in range(1, 6):
m = float(input("Enter marks in subject " + str(i) + ": "))
total += m
avg = total / 5
if avg >= 90:
grade = "A1"
elif avg >= 75:
grade = "A2"
elif avg >= 60:
grade = "B"
elif avg >= 33:
grade = "C"
else:
grade = "Fail"
print("Total =", total)
print("Average =", avg)
print("Grade =", grade)Enter marks in subject 1: 82 Enter marks in subject 2: 76 Enter marks in subject 3: 91 Enter marks in subject 4: 68 Enter marks in subject 5: 88 Total = 405.0 Average = 81.0 Grade = A2
Viva questions (3)
- Why is
float()used withinput()? Becauseinput()returns a string and marks may have decimals. - Why is the order of conditions in the elif ladder important? Only the first True condition runs, so higher ranges must be checked first.
- What would happen if
avgwere calculated inside the loop? It would be the average of only the marks read so far.
2Sale price after discount
A shop gives a discount on the marked price: 5% if the price is up to Rs 2000, 10% if it is above Rs 2000 up to Rs 5000, and 15% above Rs 5000. Input the marked price and display the discount and the sale price.
price = float(input("Enter marked price: "))
if price <= 2000:
rate = 5
elif price <= 5000:
rate = 10
else:
rate = 15
discount = price * rate / 100
sale_price = price - discount
print("Discount @", rate, "% = Rs", discount)
print("Sale price = Rs", sale_price)Enter marked price: 3600 Discount @ 10 % = Rs 360.0 Sale price = Rs 3240.0
Viva questions (2)
- Which control statement is used to choose the discount rate? The if-elif-else statement.
- What is the data type of
discount? float, because/always returns a float.
3Simple and compound interest
Input principal, annual rate of interest and time in years. Compute and display the simple interest and the compound interest (compounded annually). SI = P × R × T / 100; Amount = P × (1 + R/100)^T; CI = Amount − P.
p = float(input("Enter principal: "))
r = float(input("Enter rate of interest (% per year): "))
t = float(input("Enter time (years): "))
si = p * r * t / 100
amount = p * (1 + r / 100) ** t
ci = amount - p
print("Simple Interest = Rs", round(si, 2))
print("Compound Interest = Rs", round(ci, 2))Enter principal: 50000 Enter rate of interest (% per year): 8 Enter time (years): 3 Simple Interest = Rs 12000.0 Compound Interest = Rs 12985.6
Viva questions (3)
- Which operator is used for 'raised to the power'? The
**operator. - Why is
round(..., 2)used? To show money values with two decimal places. - Why is compound interest greater than simple interest here? Interest is also earned on the interest of previous years.
4EMI calculator
Input the loan amount, the annual interest rate and the period in years. Calculate the monthly EMI using EMI = P × r × (1 + r)^n / ((1 + r)^n − 1), where r is the monthly rate (annual rate / 12 / 100) and n is the number of months. Also display the total amount payable and the total interest.
p = float(input("Enter loan amount: "))
annual_rate = float(input("Enter annual interest rate (%): "))
years = int(input("Enter period in years: "))
r = annual_rate / 12 / 100
n = years * 12
emi = p * r * (1 + r) ** n / ((1 + r) ** n - 1)
total = emi * n
print("Monthly EMI = Rs", round(emi, 2))
print("Total payable = Rs", round(total, 2))
print("Total interest = Rs", round(total - p, 2))Enter loan amount: 500000 Enter annual interest rate (%): 9 Enter period in years: 5 Monthly EMI = Rs 10379.18 Total payable = Rs 622750.66 Total interest = Rs 122750.66
Viva questions (2)
- Why is the annual rate divided by 12 and by 100? EMI is monthly, and the rate is a percentage.
- Why are brackets needed around
(1 + r) ** n - 1? Without them, division would happen before the subtraction.
5GST bill
Input the name of an item, its price and the GST rate (5, 12, 18 or 28). Calculate CGST and SGST (each half of the GST) and print a bill showing the price, CGST, SGST and the final amount. Show an error message if the GST rate is not one of the allowed values.
item = input("Enter item name: ")
price = float(input("Enter price: "))
rate = int(input("Enter GST rate (5/12/18/28): "))
if rate in (5, 12, 18, 28):
gst = price * rate / 100
print("Item :", item)
print("Price : Rs", price)
print("CGST @", rate / 2, "% : Rs", gst / 2)
print("SGST @", rate / 2, "% : Rs", gst / 2)
print("Total : Rs", price + gst)
else:
print("Invalid GST rate")Enter item name: School bag Enter price: 1200 Enter GST rate (5/12/18/28): 18 Item : School bag Price : Rs 1200.0 CGST @ 9.0 % : Rs 108.0 SGST @ 9.0 % : Rs 108.0 Total : Rs 1416.0
Viva questions (2)
- Which operator checks that the rate is one of the allowed values? The membership operator
in. - Why is the rate read with
int()but the price withfloat()? The rate is a whole number, while a price can have paise.
6Area and perimeter of shapes (menu)
Display a menu: 1. Rectangle 2. Square 3. Circle 4. Triangle (three sides). Based on the choice, input the required measurements and display the area and the perimeter (circumference for the circle). Use Heron's formula for the triangle.
import math
print("1. Rectangle 2. Square 3. Circle 4. Triangle")
ch = int(input("Enter your choice: "))
if ch == 1:
l = float(input("Length: "))
b = float(input("Breadth: "))
print("Area =", l * b, " Perimeter =", 2 * (l + b))
elif ch == 2:
s = float(input("Side: "))
print("Area =", s * s, " Perimeter =", 4 * s)
elif ch == 3:
r = float(input("Radius: "))
print("Area =", round(math.pi * r * r, 2), " Circumference =", round(2 * math.pi * r, 2))
elif ch == 4:
a = float(input("Side a: "))
b = float(input("Side b: "))
c = float(input("Side c: "))
s = (a + b + c) / 2
area = math.sqrt(s * (s - a) * (s - b) * (s - c))
print("Area =", round(area, 2), " Perimeter =", a + b + c)
else:
print("Invalid choice")1. Rectangle 2. Square 3. Circle 4. Triangle Enter your choice: 4 Side a: 5 Side b: 6 Side c: 7 Area = 14.7 Perimeter = 18.0
Viva questions (2)
- Why is
import mathwritten at the top? To usemath.piandmath.sqrt(). - What is the role of the final
else? It handles a choice outside 1 to 4.
7Count vowels in a string
Input a sentence and count the number of vowels (both uppercase and lowercase), consonants and other characters (spaces, digits, punctuation) in it.
text = input("Enter a sentence: ")
vowels = consonants = others = 0
for ch in text:
if ch in "aeiouAEIOU":
vowels += 1
elif ("a" <= ch <= "z") or ("A" <= ch <= "Z"):
consonants += 1
else:
others += 1
print("Vowels:", vowels)
print("Consonants:", consonants)
print("Other characters:", others)Enter a sentence: Incredible India 2026! Vowels: 7 Consonants: 8 Other characters: 7
Viva questions (2)
- How does the
forloop work on a string? It takes one character at a time. - What does the condition
"a" <= ch <= "z"test? Whetherchis a lowercase letter, using a chained comparison.
8Sum of squares and multiples
(a) Find the sum of squares of the first 100 natural numbers using a loop. (b) Input a number n and a count k, and print the first k multiples of n on one line.
total = 0
for i in range(1, 101):
total += i ** 2
print("Sum of squares of first 100 natural numbers =", total)
n = int(input("Enter the number: "))
k = int(input("How many multiples? "))
for i in range(1, k + 1):
print(n * i, end=" ")
print()Sum of squares of first 100 natural numbers = 338350 Enter the number: 12 How many multiples? 8 12 24 36 48 60 72 84 96
Viva questions (2)
- Why is
range(1, 101)used and notrange(1, 100)? The stop value is excluded, so 101 is needed to include 100. - How can you verify the answer 338350? Using the formula n(n+1)(2n+1)/6 with n = 100.
Common mistakes
Using a value from
input()as a number without converting it.input()always returns a string, so writemarks = int(input("Marks: ")).Writing
=in a condition instead of==, as inif marks = 100:.=assigns a value;==compares two values.Forgetting the colon at the end of
if,elif,else,forandwhilelines, which gives aSyntaxError.Mixing tabs and spaces or indenting statements of one block unequally, which gives an
IndentationError. Use 4 spaces consistently.Expecting
range(1, 10)to include 10. The stop value is always excluded; userange(1, 11)for 1 to 10.Thinking
/gives an integer.10 / 2is5.0; use//when a whole-number quotient is required.Writing
Print,IforTrueastrue. Python is case-sensitive; keywords and built-in names must be typed exactly.Forgetting to update the control variable inside a
whileloop, which creates an infinite loop.