Class 11Computer Science · Programming with PythonFull chapter

Getting Started with Python

The whole chapter in one place — read it, then test yourself. Clear notes, a reference sheet, a practice quiz, and worked NCERT solutions & PYQs.

Python, Hello World and the Two Execution Modes

Quick answer What Python is and why it reads the way it does, the first program, and the real difference between typing code at the >>> prompt and saving it in a .py file.

Python was created by Guido van Rossum and first released in 1991. The name comes from the British comedy show Monty Python's Flying Circus, not from the snake. Python 3 arrived in 2008 and deliberately broke compatibility with Python 2 — that is why print needs brackets in every modern book, and why old code you find online sometimes refuses to run. CBSE 083 uses Python 3. Every output on this page was produced by Python 3.13.3.

Features of Python

  • Simple and readable. The syntax was designed so that correct code looks close to an English description of what it does.
  • Free and open source. Download it from python.org, use it for schoolwork or for a company, pay nothing.
  • Interpreted. The interpreter reads and executes your program statement by statement. There is no separate compile step producing an .exe. This has a consequence you will notice on day one: a run-time mistake on line 20 is only reported after lines 1 to 19 have already run and printed their output. (A syntax mistake is different — Python checks the grammar of the whole file first, so not even line 1 runs. Both cases are demonstrated in the last section.)
  • Platform independent. The same .py file runs on Windows, Linux, macOS and Android without a change.
  • Dynamically typed. You never write a type. The type belongs to the value, not to the name.
  • Large standard library. math, random and statistics ship with the installation.
  • Indentation is grammar. Other languages use { } to mark a block and treat spacing as decoration. Python uses the spacing itself. You cannot write ugly, un-indented Python that still runs.
  • Case sensitive. Marks, marks and MARKS are three different names.

The first program. Save this as hello.py and run python hello.py:

print("Hello World")

Output:

Hello World

WORKED EXAMPLE — the two execution modes. Python can be used in two ways, and CBSE asks you to name and distinguish them.

1. Interactive mode (also called the Python shell). You type one line, press Enter, and it runs at once. The prompt is >>>. A real session:

>>> print("Hello World")
Hello World
>>> 2 + 3
5
>>> "Priodemy"
'Priodemy'
>>> x = 25
>>> x * 4
100

Three things to notice. The shell printed 5 and 100 even though there was no print() — interactive mode automatically displays the value of any expression you type. It printed 'Priodemy' with quotes, because it shows you the machine's view of the object, not the human-facing text. And x = 25 printed nothing, because an assignment is a statement, not an expression — it has no value to show.

2. Script mode. The same lines saved in a file demo.py:

# demo.py - script mode
2 + 3
"Priodemy"
print(2 + 3)
print("Priodemy")

Real output of python demo.py:

5
Priodemy

The bare 2 + 3 and "Priodemy" were computed and thrown away silently. In script mode nothing appears on screen unless you call print(). This single fact explains most "my program runs but shows nothing" complaints. Note also that print("Priodemy") gave Priodemy without quotes, unlike the shell.

Use interactive mode to test one idea — "what does 17 % 5 give?". Use script mode for anything you want to keep, re-run or submit, because interactive work vanishes when you close the window.

Python character set. The characters Python understands in source code: letters A-Z a-z, digits 0-9, special symbols such as + - * / % = < > ( ) [ ] { } , : . ' " # _ \ @ & | ! ~ ^ ;, and whitespace (space, tab, newline). Python 3 source files are UTF-8 by default, so a string may hold any script in the world, and the interpreter will even accept an identifier written in Devanagari or Tamil. Data in Indian languages is therefore no problem at all:

naam = "Rohit"
print(naam, 500)
Rohit 500

Legal is not the same as sensible: keep identifiers in English so your code opens correctly on any machine and any examiner can read it.

Case sensitivity, proved:

Marks = 90
marks = 45
print(Marks, marks)
print(Marks == marks)
90 45
False

WORKED EXAMPLE — comments. A comment is text Python ignores. It starts at # and runs to the end of that line. Python has no /* ... */ block comment.

# fees.py : prints the fee slip for one student
# Author: Ananya, Class XI-A

name = "Ananya Sharma"     # student name
tuition = 12000            # rupees per term
lab = 1500                 # lab fee

"""
This triple-quoted string is not attached to anything,
so Python builds it and throws it away. Students often
use it as a multi-line comment.
"""

total = tuition + lab
print("Student:", name)
print("Total fee: Rs", total)
Student: Ananya Sharma
Total fee: Rs 13500

The triple-quoted block is not a comment — it is a real string object that gets created and discarded. It works in practice, but if an exam asks "how does Python mark a comment?", the answer is #.

Long statements. A statement normally ends at the end of the line. To spread one over several lines, use a single backslash as the very last character of the line, or better, use brackets:

total = 1200 + \
        800 + \
        450
print(total)

subjects = ["Physics",
            "Chemistry",
            "CS"]
print(subjects)
2450
['Physics', 'Chemistry', 'CS']

Prefer the bracket form. A single invisible space after a backslash breaks the program with SyntaxError: unexpected character after line continuation character, and nothing on screen tells you that the culprit is a space you cannot see.

Run a script python filename.py Command Prompt / terminal · Run it from the folder holding the file. Nothing appears on screen unless the program calls print().
Interactive prompt >>> statement (continuation prompt: ...) The shell auto-displays the value of any expression. An assignment shows nothing because it has no value.
print() print(obj1, obj2, ..., sep=' ', end='\n') Joins the items with sep, then appends end. Default sep is one space, default end is a newline.
Comment # everything after the hash, to end of line There is no /* */ in Python. A """triple-quoted string""" is a string object, not a comment.
Line continuation one backslash as the last character of the line, or wrap the expression in ( ) [ ] { } Brackets are safer: a stray space after the backslash gives SyntaxError: unexpected character after line continuation character.
Case rule Marks != marks != MARKS All keywords are lowercase except True, False and None.
Remember
  • Python is interpreted, dynamically typed, case sensitive, free and platform independent; indentation is part of its grammar, not decoration.
  • Interactive mode (>>>) echoes the value of every expression automatically; script mode prints absolutely nothing unless you call print().
  • Interactive mode shows strings with quotes ('Priodemy'); print() shows them without.
  • A comment starts at # and ends with the line. Python has no block-comment syntax; a triple-quoted string used as one is really a string object.
  • Source is UTF-8, so strings (and even identifiers) may use any script, but keep names in English for portability and readability.

Tokens, Variables and the l-value / r-value Idea

Quick answer The five kinds of token Python recognises, the rules for naming things, and why price*3 = total is a syntax error while total = price*3 is not.

When the interpreter reads a line it first chops it into tokens — the smallest units that mean something on their own. In total = price * 3 the tokens are total, =, price, * and 3. CBSE lists five kinds: keyword, identifier, literal, operator, punctuator.

1. Keywords are words reserved by the language. You cannot use them as names. WORKED EXAMPLE:

import keyword
print("Total keywords:", len(keyword.kwlist))
print(keyword.kwlist)
print("Soft keywords:", keyword.softkwlist)
print(keyword.iskeyword("for"), keyword.iskeyword("For"), keyword.iskeyword("marks"))
Total keywords: 35
['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']
Soft keywords: ['_', 'case', 'match', 'type']
True False False

Two honest points. The count is version-dependent — older textbooks say 33 because older Pythons had fewer. Do not memorise a number; run keyword.kwlist on whatever Python you are using. And iskeyword("For") is False: keywords are lowercase, so For is an ordinary name. The four "soft keywords" are special only inside particular statements and are still usable as variable names.

2. Identifiers are the names you invent for variables. Rules: start with a letter or underscore, then letters, digits or underscores; no spaces; no other punctuation; cannot be a keyword; case matters. WORKED EXAMPLE — each line prints the name, then isidentifier() (has it the right shape?), then iskeyword() (is it reserved?):

import keyword

print("marks        ->", "marks".isidentifier(), keyword.iskeyword("marks"))
print("_total       ->", "_total".isidentifier(), keyword.iskeyword("_total"))
print("roll1        ->", "roll1".isidentifier(), keyword.iskeyword("roll1"))
print("1roll        ->", "1roll".isidentifier(), keyword.iskeyword("1roll"))
print("total marks  ->", "total marks".isidentifier(), keyword.iskeyword("total marks"))
print("class        ->", "class".isidentifier(), keyword.iskeyword("class"))
print("Marks        ->", "Marks".isidentifier(), keyword.iskeyword("Marks"))
print("Rs_fee       ->", "Rs_fee".isidentifier(), keyword.iskeyword("Rs_fee"))
marks        -> True False
_total       -> True False
roll1        -> True False
1roll        -> False False
total marks  -> False False
class        -> True True
Marks        -> True False
Rs_fee       -> True False

Read the class row carefully. The first flag is True because class has the right shape for a name — but the second flag is True as well, so it is reserved and cannot actually be used. A name is usable only when isidentifier() is True and iskeyword() is False. 1roll fails on the first flag (starts with a digit) and total marks fails on it too (contains a space).

3. Literals are fixed values written directly in the source. WORKED EXAMPLE:

a = 25            # decimal integer literal
b = 0b1101        # binary
c = 0o17          # octal
d = 0xFF          # hexadecimal
e = 3.14          # floating point
f = 2.5e3         # exponent form
g = 3 + 4j        # complex
h = 'UPI'         # string (single quotes)
i = "IRCTC"       # string (double quotes)
j = True          # boolean
k = None          # None literal
m = 1_00_000      # underscores allowed in numeric literals

print(a, b, c, d)
print(e, f, g, g.real, g.imag)
print(h, i, j, k, m)
25 13 15 255
3.14 2500.0 (3+4j) 3.0 4.0
UPI IRCTC True None 100000

Notice 0b1101 printed as 13 and 0xFF as 255: the prefix only tells Python how to read the digits, and the value is stored as an ordinary integer. The underscores in 1_00_000 are ignored — useful for lakh/crore grouping in Indian amounts.

4. Operators — + - * / // % ** = == != < > <= >= and or not is is not in not in and the augmented forms. Full treatment in the operators section.

5. Punctuators (also called delimiters, separators) are the marks that shape a statement rather than compute anything: ( ) [ ] { } , : . ; @ = ' " # and the augmented assignment symbols += -= *= and so on. The colon after if, the comma between arguments and the brackets around a list are all punctuators.

Variables. Python has no declaration statement. A variable comes into existence the moment you assign to it, and the type of the value decides the type:

roll = 24        # roll is an int now
roll = "XI-A"    # the same name now refers to a str - perfectly legal

The right mental picture is not "a box holding 24". It is "a name-tag stuck on an object". = does not copy anything into a box; it points a name at an object. Everything strange about mutability in the next section follows from this one idea.

WORKED EXAMPLE — l-value and r-value. In an assignment, whatever is on the left is the l-value (the location being named) and whatever is on the right is the r-value (the value being computed). The r-value is worked out completely first, then the name is bound to the result.

price = 250          # price is the l-value, 250 is the r-value
qty = 3
total = price * qty  # total is l-value, price*qty is r-value
print(total)

x = y = z = 0        # chained assignment
print(x, y, z)

p, q = 10, 20        # multiple assignment
p, q = q, p          # swap - RHS is fully evaluated first
print(p, q)
750
0 0 0
20 10

The swap works with no temporary variable precisely because the r-value q, p is fully evaluated into (20, 10) before either name is rebound.

An expression can be an r-value but never an l-value. This is a deliberate error, and it is worth seeing:

price = 250
price * 3 = total
  File "C:\pytmp\lvalue.py", line 2
    price * 3 = total
    ^^^^^^^^^
SyntaxError: cannot assign to expression here. Maybe you meant '==' instead of '='?

price * 3 is a computed value; there is no place called "price times three" to store anything in. Only a name (or an item of a mutable object such as L[0] or d["CS"]) can sit on the left.

Keyword list import keyword; keyword.kwlist Returns the list of reserved words for YOUR Python version. 35 in Python 3.13.
keyword.iskeyword() keyword.iskeyword(s) -> bool Case sensitive: iskeyword('for') is True, iskeyword('For') is False.
str.isidentifier() s.isidentifier() -> bool Checks the SHAPE only. 'class'.isidentifier() is True even though class is reserved - test both.
Identifier rule (letter | _) followed by any number of (letter | digit | _) No spaces, no . $ @ or other punctuation, cannot begin with a digit, case sensitive.
Assignment l-value = r-value l-value must be a name, L[i] or d[key]. 'price * 3 = total' raises SyntaxError: cannot assign to expression.
Multiple / chained a, b = b, a | x = y = z = 0 The whole right side is evaluated first, so the swap needs no temporary variable.
Remember
  • A token is the smallest meaningful unit of source code; the five kinds are keyword, identifier, literal, operator and punctuator.
  • Python 3.13 has 35 keywords - check with keyword.kwlist rather than memorising a number, since older versions had fewer.
  • A name is usable only if s.isidentifier() is True AND keyword.iskeyword(s) is False; 'class' passes the first test and fails the second.
  • = binds a name to an object; it does not copy a value into a box. This picture explains everything in the next section.
  • The left of an assignment is the l-value and must be a name or an item of a mutable object; the right is the r-value and is fully evaluated first, which is why a, b = b, a swaps without a temp.

Data Types, and Why Some Values Can Be Changed and Some Cannot

Quick answer Every Class 11 data type with type() proof, then id() used to show exactly what mutable and immutable mean and why 'is' and '==' are different questions.

In Python a type belongs to the value, not to the name. Ask any object what it is with type(). WORKED EXAMPLE — every type in the Class 11 syllabus:

roll      = 24
percent   = 88.5
z         = 3 + 4j
passed    = True
name      = "Kavya"
subjects  = ["Physics", "Chemistry", "CS"]
best3     = ("CS", "Maths", "Physics")
marks     = {"CS": 95, "Maths": 88, "Physics": 79}
remark    = None

print(roll, type(roll))
print(percent, type(percent))
print(z, type(z))
print(passed, type(passed))
print(name, type(name))
print(subjects, type(subjects))
print(best3, type(best3))
print(marks, type(marks))
print(remark, type(remark))
24 
88.5 
(3+4j) 
True 
Kavya 
['Physics', 'Chemistry', 'CS'] 
('CS', 'Maths', 'Physics') 
{'CS': 95, 'Maths': 88, 'Physics': 79} 
None 
CategoryTypeExampleMutable?
Numberint24, -7, 0b1101No
Numberfloat88.5, 2.5e3No
Numbercomplex3+4jNo
BooleanboolTrue, FalseNo
Sequencestr"Kavya"No
Sequencelist[95, 88, 79]Yes
Sequencetuple(95, 88, 79)No
Mappingdict{"CS": 95}Yes
NoneNoneTypeNoneNo

Numbers. Python integers have no size limit — 2 ** 100 is exact. Floats are stored in binary, so decimal fractions are approximations. This surprises everybody once:

print(0.1 + 0.2)
print(0.1 + 0.2 == 0.3)
print(round(0.1 + 0.2, 2) == 0.3)
print(7 / 3)
0.30000000000000004
False
True
2.3333333333333335

One-tenth cannot be written exactly in binary, exactly as one-third cannot be written exactly in decimal. This is not a Python bug; it is how every language stores floats. Never test money or marks with == on floats — round first.

Complex numbers use j, not i, because engineers use j. z.real and z.imag pull the parts out, and both come back as floats.

bool is really an int. True is 1 and False is 0:

print(True + True, True == 1, False == 0, isinstance(True, int))
2 True True True

This is why (a > b) + (b > c) can count how many conditions held — a favourite exam trick.

None is a single object meaning "no value at all". It is not 0, not False and not the empty string; it is its own type, NoneType.

id() and identity. Every object has an identity number, obtained with id(). Think of it as the object's address. Two names holding the same id are two tags on one object.

WORKED EXAMPLE — mutable vs immutable, proved with id(). (Your id numbers will be different from these on every run; only the pattern of same/different matters.)

# ---- IMMUTABLE: string ----
s = "IRCTC"
print("s        =", s, " id =", id(s))
s = s + " Rail"          # NOT modification - a brand new string object
print("s (new)  =", s, " id =", id(s))

print()
# ---- MUTABLE: list ----
L = ["Physics", "Chemistry"]
print("L        =", L, " id =", id(L))
L.append("CS")           # same object changed in place
print("L (same) =", L, " id =", id(L))

print()
# ---- IMMUTABLE: int ----
n = 10
print("n        =", n, " id =", id(n))
n = n + 1
print("n (new)  =", n, " id =", id(n))
s        = IRCTC  id = 2149590805232
s (new)  = IRCTC Rail  id = 2149591006768

L        = ['Physics', 'Chemistry']  id = 2149588446656
L (same) = ['Physics', 'Chemistry', 'CS']  id = 2149588446656

n        = 10  id = 140712570856648
n (new)  = 11  id = 140712570856680

Read the ids, not the values. The string's id changed: s + " Rail" built a completely new string and moved the name-tag onto it; the original "IRCTC" was never touched. The list's id stayed the same: append reached into the existing object and altered it. The int behaves like the string. That is the whole definition — immutable means "operations produce a new object", mutable means "the object itself can be edited in place".

One detail worth noticing while you are here: L.append("CS") printed nothing on its own line. The list methods that edit in place — append, insert, extend, sort, reverse, and a dictionary's update and clear — change the object and hand back None. Writing L = L.append("CS") therefore throws the list away and leaves L equal to None. Call them as a statement, never as a value.

WORKED EXAMPLE — the aliasing trap this creates. Because = only moves name-tags, this catches every beginner:

a = [10, 20, 30]
b = a                 # b is NOT a copy - both names point to the SAME list
b.append(40)
print("a =", a)
print("b =", b)
print("same object?", a is b, "| ids:", id(a) == id(b))

t = (10, 20, 30)
t[0] = 99
a = [10, 20, 30, 40]
b = [10, 20, 30, 40]
same object? True | ids: True
Traceback (most recent call last):
  File "C:\pytmp\alias.py", line 9, in 
    t[0] = 99
    ~^^^
TypeError: 'tuple' object does not support item assignment

You appended to b and a changed, because there was only ever one list. With an immutable type this cannot happen — which is exactly why tuples are safer for data that must not be edited (a list of exam subjects, a fixed set of GST rates), and why dictionary keys must be immutable.

The one nuance examiners love: a tuple is immutable, but it only promises that the references inside it will not change. If one of them points at a list, that list is still mutable:

t = (1, 2, [3, 4])
t[2].append(5)
print(t)
(1, 2, [3, 4, 5])

No rule was broken: t[2] still refers to the same list object. Only the list's contents changed.

WORKED EXAMPLE — is versus ==. == asks "do these have the same value?". is asks "are these the very same object?". They are different questions.

a = [1, 2, 3]
b = [1, 2, 3]
c = a
print("a == b :", a == b)     # same VALUE
print("a is b :", a is b)     # different OBJECTS
print("a == c :", a == c)
print("a is c :", a is c)     # same object
print("ids:", id(a), id(b), id(c))
a == b : True
a is b : False
a == c : True
a is c : True
ids: 1506432048000 1506432201600 1506432048000

a and b hold equal lists that live at different addresses. a is b is False and a == b is True — that pair of answers is the whole point of the question.

Warning: never use is to compare numbers or strings. Python quietly reuses small integers and short strings to save memory, so is sometimes gives True by accident. A real shell session:

>>> x = 1000
>>> y = 1000
>>> x is y
False
>>> x == y
True
>>> a = 100
>>> b = 100
>>> a is b
True

Same code shape, opposite answers, purely because Python caches the small integers. Python 3.13 will even warn you: writing 10 is 10.0 in a file produces SyntaxWarning: "is" with 'int' literal. Did you mean "=="? and then prints False. Use == for values. Use is only for identity questions and for x is None.

type() type(obj) -> class type(True) is bool, type(10/5) is float, type((10)) is int but type((10,)) is tuple.
id() id(obj) -> int The object's identity/address. Different on every run - compare two ids, never memorise one.
Immutable types int, float, complex, bool, str, tuple, None Rebinding builds a new object. Dictionary keys must be hashable, which at Class 11 level means immutable.
Mutable types list, dict Methods like append(), and item assignment L[0] = x or d[k] = v, change the object in place and return None.
is vs == x is y -> same object? x == y -> same value? is is equivalent to id(x) == id(y). Use == for values; use is only with None.
Falsy values bool(x) is False for: 0, 0.0, 0j, '', [], (), {}, None Everything else is True - including the string '0', the string 'False' and the list [0].
Remember
  • A type belongs to the value, not to the name; type() reports it and id() reports which object a name currently points at.
  • Immutable (int, float, complex, bool, str, tuple, None): any operation builds a NEW object, so id() changes. Mutable (list, dict): the object is edited in place and id() stays the same.
  • b = a does not copy a list. Both names tag the same object, so b.append() is visible through a.
  • In-place methods (append, insert, extend, sort, reverse, update, clear) return None, so L = L.append(x) destroys the list. Call them as a statement.
  • == compares values, is compares identity. Two equal lists give a == b True but a is b False. Never use is on numbers or strings; small ints are cached and the answer is unreliable.

Operators, Expressions and Precedence

Quick answer All seven operator families with executed examples, the negative floor-division rule, short-circuit logic, and a precedence table you can evaluate any expression with.

An expression is anything that produces a value: 2 + 3, marks >= 33, "Rs " + str(250). A statement is a complete instruction: total = 2 + 3, print(total). Every expression can appear inside a statement; a statement cannot appear inside an expression.

1. Arithmetic operators. WORKED EXAMPLE:

a, b = 17, 5
print("a + b  =", a + b)
print("a - b  =", a - b)
print("a * b  =", a * b)
print("a / b  =", a / b)      # true division -> always float
print("a // b =", a // b)     # floor division
print("a % b  =", a % b)      # remainder
print("a ** b =", a ** b)     # exponent
print()
print("-17 // 5 =", -17 // 5)   # floors TOWARDS minus infinity
print("-17 %  5 =", -17 % 5)
print("17 / 1   =", 17 / 1, type(17 / 1))
print("7.0 // 2 =", 7.0 // 2, type(7.0 // 2))
a + b  = 22
a - b  = 12
a * b  = 85
a / b  = 3.4
a // b = 3
a % b  = 2
a ** b = 1419857

-17 // 5 = -4
-17 %  5 = 3
17 / 1   = 17.0 
7.0 // 2 = 3.0 

Three rules worth writing down. / always gives a float, even 17 / 1 which is 17.0. // gives an int only when both operands are ints; 7.0 // 2 is 3.0. And -17 // 5 is -4, not -3: Python floors towards minus infinity rather than truncating towards zero the way C and Java do. The remainder then takes the sign of the divisor, so -17 % 5 is +3, and the identity a == (a // b) * b + (a % b) stays true: (-4) * 5 + 3 = -17.

2. Relational operators — < > <= >= == != — produce True or False. 3. Logical operators — and or not. WORKED EXAMPLE:

m1, m2 = 78, 91
print(m1 > m2, m1 < m2, m1 == m2, m1 != m2, m1 >= 78, m2 <= 90)
print("chained:", 33 <= m1 <= 100)
print("strings:", "Amit" < "Bhavna", "amit" < "Amit")
print("bool is int:", True + True, True == 1, False == 0)
print()
print(0 or "fallback")
print("Rahul" and 0)
print(not 0, not "", not "x")
print(10 > 5 and 3 > 7, 10 > 5 or 3 > 7)
False True False True True False
chained: True
strings: True False
bool is int: 2 True True

fallback
0
True True False
False True

Python allows chained comparisons: 33 <= m1 <= 100 means exactly what it says in maths, unlike C where it would give nonsense. Strings compare by Unicode code point, character by character, so "Amit" < "Bhavna" is True (A before B) but "amit" < "Amit" is False — lowercase letters come after uppercase.

Look at 0 or "fallback" giving fallback and "Rahul" and 0 giving 0. and and or return one of their operands, not necessarily True/False. They also short-circuit: or stops as soon as something is true, and stops as soon as something is false. This runs without error even though the right side would divide by zero:

print(10 > 5 or 3 / 0 == 1)
True

10 > 5 was already True, so 3 / 0 was never evaluated.

4. Assignment and 5. augmented assignment. WORKED EXAMPLE — a bank balance:

bal = 5000
bal += 2500      # bal = bal + 2500
print("after credit :", bal)
bal -= 1200
print("after debit  :", bal)
bal *= 2
print("doubled      :", bal)
bal //= 3
print("floor div    :", bal)
bal %= 1000
print("modulo       :", bal)
bal **= 2
print("squared      :", bal)
share = 900
share /= 4       # /= ALWAYS makes it a float
print("after /=     :", share, type(share))
L = [1, 2]
print("id before:", id(L))
L += [3]
print(L, "id after +=:", id(L))
L = L + [4]
print(L, "id after + :", id(L))
after credit : 7500
after debit  : 6300
doubled      : 12600
floor div    : 4200
modulo       : 200
squared      : 40000
after /=     : 225.0 
id before: 2852657081792
[1, 2, 3] id after +=: 2852657081792
[1, 2, 3, 4] id after + : 2852658754432

x += y is shorthand for x = x + y and saves you naming x twice. Note that /= follows the same rule as / and turns an int into a float. On a list there is a real difference too: L += [3] kept the same id (it edited the list in place, like extend), while L = L + [4] built a new list at a new id. Anyone else holding the old name sees the += change but not the + one.

6. Identity operators is and is not compare object identity. 7. Membership operators in and not in ask whether a value occurs in a sequence. WORKED EXAMPLE:

subjects = ["Physics", "Chemistry", "CS", "Maths"]
print("CS" in subjects)
print("Biology" in subjects)
print("Biology" not in subjects)

marks = {"CS": 95, "Maths": 88}
print("CS" in marks)        # searches KEYS
print(95 in marks)          # 95 is a value, not a key
print(95 in marks.values())

s = "IRCTC ticket"
print("ticket" in s, "TICKET" in s)

t = (10, 20, 30)
print(20 in t, 40 not in t)

remark = None
print(remark is None, subjects is not None)
True
False
True
True
False
True
True False
True True
True True

The trap is the dictionary: in searches keys only, so 95 in marks is False even though 95 is sitting right there as a value. Ask for marks.values() explicitly. On a string, in checks for a substring and is case sensitive. The last line is the one correct everyday use of the identity pair: x is None and x is not None.

Precedence and associativity. When several operators meet, precedence decides who acts first; associativity decides ties. Highest to lowest, for the operators in the Class 11 syllabus:

LevelOperatorsAssociativity
1 (highest)( ) grouping—
2**Right to left
3+x, -x (unary)Right to left
4*, /, //, %Left to right
5+, - (binary)Left to right
6< <= > >= == !=, is, is not, in, not inLeft to right (chained)
7not—
8andLeft to right
9 (lowest)orLeft to right

WORKED EXAMPLE — precedence in action:

print(2 + 3 * 4)            # * before +
print((2 + 3) * 4)
print(2 ** 3 ** 2)          # ** is RIGHT associative -> 2**(3**2)
print((2 ** 3) ** 2)
print(-2 ** 2)              # ** binds tighter than unary minus
print((-2) ** 2)
print(10 - 4 - 3)           # - is LEFT associative
print(100 / 10 * 2)         # same level -> left to right
print(20 // 3 % 4)
print(True or False and False)   # 'and' before 'or'
print((True or False) and False)
print(2 + 3 > 4 and 5 % 2 == 1)  # arithmetic > relational > logical
14
20
512
64
-4
4
3
20.0
2
True
False
True

The two rows to memorise: 2 ** 3 ** 2 is 512 because ** groups right-to-left (2 ** 9), not 64. And -2 ** 2 is -4 because ** outranks the minus sign, so Python computes -(2 ** 2).

How to evaluate an expression in an exam. Take 2 + 3 > 4 and 5 % 2 == 1. Arithmetic first: 2 + 3 is 5 and 5 % 2 is 1. Then relational: 5 > 4 is True, 1 == 1 is True. Then logical: True and True is True. Write each of those three lines out; step marks are given for the working, not only the answer.

Arithmetic set + - * / // % ** / true division (always float), // floor division, % remainder, ** exponent.
Negative floor division a // b floors toward -inf; a % b takes the sign of b -17 // 5 = -4 and -17 % 5 = 3, so (a//b)*b + a%b == a still holds. C and Java give -3 and -2.
Augmented assignment x += y x -= y x *= y x /= y x //= y x %= y x **= y Shorthand for x = x op y. /= always produces a float. On a list, += mutates in place (id unchanged) while + builds a new list.
Identity x is y x is not y Compares id(), not value. Reliable only for None and for real 'same object' questions.
Membership v in seq v not in seq Sequences: element (or substring, for str). Dictionary: searches KEYS only. Case sensitive on strings.
Precedence, high to low () > ** > unary - > * / // % > + - > comparisons/is/in > not > and > or ** is right-associative; everything else at the same level runs left to right.
Remember
  • / always returns a float; // returns an int only when both operands are ints. // floors towards minus infinity, so -17 // 5 is -4 and -17 % 5 is +3.
  • ** is right-associative and outranks unary minus: 2 ** 3 ** 2 is 512 and -2 ** 2 is -4.
  • and / or return an operand rather than a boolean, and they short-circuit: 10 > 5 or 3/0 == 1 prints True without ever dividing by zero.
  • On a dictionary, 'in' searches keys only - 95 in marks is False even when 95 is a value; use marks.values(). The identity pair is / is not is for x is None, not for comparing numbers.
  • Precedence order: () then ** then unary +/- then * / // % then binary + - then comparisons then not then and then or.

Input, Output, Type Conversion and the Three Kinds of Error

Quick answer print() and its sep/end, why input() always hands you a string, implicit versus explicit conversion, and syntax, logical and run-time errors each demonstrated with real output.

Output with print(). print() takes any number of items, joins them with sep (default one space) and finishes with end (default a newline). WORKED EXAMPLE:

name, marks = "Vikram", 87
print("Name:", name, "Marks:", marks)
print("Name:", name, "Marks:", marks, sep="")
print(1, 2, 3, sep="-")
print("Loading", end="")
print("...", end="")
print(" done")
print("Rs", 250, sep="")
print()
print("Total =", 12000 + 1500)
Name: Vikram Marks: 87
Name:VikramMarks:87
1-2-3
Loading... done
Rs250

Total = 13500

end="" is how three print() calls produced one line. A bare print() prints just the newline, giving a blank line.

Escape sequences let you put special characters inside a string. Each one is a single backslash followed by one letter or symbol:

print("Roll\tName\tMarks")
print("01\tKavya\t95")
print("Line1\nLine2")
print("She said \"Namaste\"")
print('It\'s fine')
print("C:\\Users\\student")
Roll	Name	Marks
01	Kavya	95
Line1
Line2
She said "Namaste"
It's fine
C:\Users\student

The last line is the one students get wrong: to print one backslash you must write two, because a lone backslash is read as the start of an escape sequence.

Input with input(). This is the single biggest source of beginner bugs in Class 11, so read it twice: input() always returns a string. Always. Even if the user types 12.

WORKED EXAMPLE — the classic bug. (The extra print() lines just echo what was typed, so the printed transcript matches what you would see on your own screen.)

a = input("Enter first number : ")
print(a)                      # echo, so the transcript shows what was typed
b = input("Enter second number: ")
print(b)
print("a + b       =", a + b)
print("type(a)     =", type(a))
print("Correct sum =", int(a) + int(b))
Enter first number : 12
Enter second number: 7
a + b       = 127
type(a)     = 
Correct sum = 19

The student typed 12 and 7 and got 127. Nothing went wrong — a and b are the strings "12" and "7", and + on two strings means join. The fix is to convert at the moment of reading: a = int(input("Enter first number: ")). Wrap the input() in int() or float() and the bug can never occur.

Type conversion. Implicit (also called coercion) is done by Python without being asked, always widening along the chain bool → int → float → complex so no information is lost. Explicit (type casting) is when you call int(), float(), str(), bool() or complex() yourself. WORKED EXAMPLE:

# IMPLICIT - Python widens automatically
x = 7          # int
y = 2.5        # float
z = x + y
print(z, type(z))
print(True + 10, type(True + 10))
print(3 + (2 + 3j), type(3 + (2 + 3j)))

# EXPLICIT - you ask for it
print(int("45"), type(int("45")))
print(int(9.99))                # truncates towards zero, does NOT round
print(int(-9.99))
print(float("3.5"), float(7))
print(str(250) + " rupees")
print(bool(0), bool(0.0), bool(""), bool([]), bool("0"), bool([0]))
print(complex(3, 4))
print(int("1101", 2), int("FF", 16))
9.5 
11 
(5+3j) 
45 
9
-9
3.5 7.0
250 rupees
False False False False True True
(3+4j)
13 255

Two gotchas here. int(9.99) is 9 and int(-9.99) is -9: int() chops the decimal part off, it does not round. Use round() if you want rounding. And bool("0") is True — the string "0" is one character long, and any non-empty string is true. Only 0, 0.0, 0j, "", [], (), {} and None are false.

Also, int() refuses a decimal string:

print(int("45.5"))
Traceback (most recent call last):
  File "C:\pytmp\convfail.py", line 1, in 
    print(int("45.5"))
          ~~~^^^^^^^^
ValueError: invalid literal for int() with base 10: '45.5'

The fix is int(float("45.5")), which gives 45. Python will not guess your intention when data would be lost.

Now the three kinds of error. CBSE asks you to classify errors, and the classification is about when the problem is discovered.

1. Syntax error — found before anything runs. The code breaks the grammar of the language, so the interpreter cannot even begin.

marks = 75
if marks > 40
    print("Pass")
  File "C:\pytmp\err_syntax.py", line 2
    if marks > 40
                 ^
SyntaxError: expected ':'

Note that marks = 75 never executed. A syntax error kills the whole file. Missing colon, unbalanced bracket, unterminated quote and wrong indentation all land here:

marks = 75
if marks > 40:
print("Pass")
  File "C:\pytmp\err_indent.py", line 3
    print("Pass")
    ^^^^^
IndentationError: expected an indented block after 'if' statement on line 2

2. Run-time error (exception) — the grammar is fine, but something goes wrong while running. Output already produced stays on the screen; the program stops at that line.

total = 450
subjects = 0
print("Average =", total / subjects)
Traceback (most recent call last):
  File "C:\pytmp\err_runtime.py", line 3, in 
    print("Average =", total / subjects)
                       ~~~~~~^~~~~~~~~~
ZeroDivisionError: division by zero

The ~~~~~^~~~~ markers under the line are Python 3.11+ pointing at the exact sub-expression that failed. Common run-time errors you should be able to name:

prince = 250
print(price * 2)
Traceback (most recent call last):
  File "C:\pytmp\err_name.py", line 2, in 
    print(price * 2)
          ^^^^^
NameError: name 'price' is not defined. Did you mean: 'prince'?
age = input("Enter age: ")
print("Next year you will be", age + 1)
Enter age: 17
Traceback (most recent call last):
  File "C:\pytmp\err_type.py", line 2, in 
    print("Next year you will be", age + 1)
                                   ~~~~^~~
TypeError: can only concatenate str (not "int") to str
subjects = ["Physics", "Chemistry", "CS"]
print(subjects[3])
Traceback (most recent call last):
  File "C:\pytmp\err_index.py", line 2, in 
    print(subjects[3])
          ~~~~~~~~^^^
IndexError: list index out of range

That TypeError is the input() trap again, this time caught by Python instead of silently giving a wrong answer. The IndexError is the reminder that a three-item list has positions 0, 1 and 2 only.

3. Logical error — the program runs perfectly and prints the wrong answer. Python cannot help you here at all, which is what makes these the dangerous ones.

p, c, m = 80, 75, 91
average = p + c + m / 3          # BUG: missing brackets
print("Average =", average)
Average = 185.33333333333334

No error, no warning, exit code 0 — and an average of 185 out of 100. Because / outranks +, Python computed 80 + 75 + (91/3). Corrected:

p, c, m = 80, 75, 91
average = (p + c + m) / 3
print("Average =", average)
Average = 82.0

The only defence against a logical error is checking output against a value you worked out by hand. Here, three marks near 80 must average near 80; 185 is impossible, and noticing that is the skill.

KindFound whenDoes the program run?Example
Syntax errorBefore execution startsNot one line runsMissing : after if
Run-time errorDuring executionRuns, then stops at that lineZeroDivisionError, NameError, TypeError, ValueError, IndexError
Logical errorOnly when you check the answerRuns fully, output is wrongp + c + m / 3 for an average
input() input(prompt) -> str ALWAYS a string, even when the user types digits. Convert at once: n = int(input('Marks: ')).
print() print(*objects, sep=' ', end='\n') sep goes between items, end at the finish. print() alone prints a blank line.
Explicit conversion int(x[, base]) float(x) str(x) bool(x) complex(re, im) int('FF', 16) is 255. int() truncates towards zero; it does not round.
Implicit conversion bool -> int -> float -> complex Python widens the narrower operand so nothing is lost. True + 10 is 11; 7 + 2.5 is 9.5.
Escape sequences \n newline \t tab \\ one backslash \' quote \" double quote Always ONE backslash plus one character. Two backslashes in the source print as one on screen.
Three error kinds Syntax = grammar broken, nothing runs | Run-time = valid code fails mid-way (Traceback) | Logical = runs fine, answer wrong Only the first two are reported by Python. Logical errors are found by checking output against a hand-computed value.
Remember
  • input() ALWAYS returns a str. Typing 12 and 7 and printing a + b gives 127, not 19. Wrap the call: int(input("...")).
  • print() joins items with sep (default one space) and appends end (default a newline); end="" keeps several print() calls on one line.
  • Implicit conversion widens automatically along bool -> int -> float -> complex. Explicit conversion is int(), float(), str(), bool(), complex().
  • int() truncates rather than rounds: int(9.99) is 9 and int(-9.99) is -9. int("45.5") raises ValueError - use int(float("45.5")).
  • Syntax errors stop the file before line 1 runs; run-time errors stop it partway with a Traceback; logical errors let it finish and quietly print a wrong answer.

The formula sheet

Every formula in this chapter, in one place — screenshot it before your exam.

python filename.py
Run a scriptCommand Prompt / terminal
>>> statement (continuation prompt: ...)
Interactive prompt
print(obj1, obj2, ..., sep=' ', end='\n')
print()
# everything after the hash, to end of line
Comment
one backslash as the last character of the line, or wrap the expression in ( ) [ ] { }
Line continuation
Marks != marks != MARKS
Case rule
import keyword; keyword.kwlist
Keyword list
keyword.iskeyword(s) -> bool
keyword.iskeyword()
s.isidentifier() -> bool
str.isidentifier()
(letter | _) followed by any number of (letter | digit | _)
Identifier rule
l-value = r-value
Assignment
a, b = b, a | x = y = z = 0
Multiple / chained
type(obj) -> class
type()
id(obj) -> int
id()
int, float, complex, bool, str, tuple, None
Immutable types
list, dict
Mutable types
x is y -> same object? x == y -> same value?
is vs ==
bool(x) is False for: 0, 0.0, 0j, '', [], (), {}, None
Falsy values
+ - * / // % **
Arithmetic set
a // b floors toward -inf; a % b takes the sign of b
Negative floor division
x += y x -= y x *= y x /= y x //= y x %= y x **= y
Augmented assignment
x is y x is not y
Identity
v in seq v not in seq
Membership
() > ** > unary - > * / // % > + - > comparisons/is/in > not > and > or
Precedence, high to low
input(prompt) -> str
input()
print(*objects, sep=' ', end='\n')
print()
int(x[, base]) float(x) str(x) bool(x) complex(re, im)
Explicit conversion
bool -> int -> float -> complex
Implicit conversion
\n newline \t tab \\ one backslash \' quote \" double quote
Escape sequences
Syntax = grammar broken, nothing runs | Run-time = valid code fails mid-way (Traceback) | Logical = runs fine, answer wrong
Three error kinds

Test yourself

Tap an answer to check it instantly — you'll see why it's right, and what to revise if it isn't.

0 correct · 0/12 answered
Q1

Predict the output:x = 5y = "5"print(x * 3, y * 3)

Q2

Predict the output:a = [1, 2, 3]b = ab += [4]print(a, len(a))

Q3

Predict the output:print(15 // 4, 15 % 4, -15 // 4, -15 % 4)

Q4

Predict the output:print(2 ** 3 ** 2, -3 ** 2)

Q5

Predict the output:a = 7a += 3a //= 2a **= 2print(a)

Q6

Predict the output:t = (1, 2, [3, 4])t[2].append(5)print(t)

Q7

Predict the output:d = {"a": 1, "b": 2}print("a" in d, 1 in d, 1 in d.values())

Q8

Predict the output:print(type((10)), type((10,)))

Q9

Predict the output:print(bool(""), bool(" "), bool(0.0), bool("False"))

Q10

A program reads num = input("Enter marks: ") and the user types 87. What does type(num) report?

Q11

Which of the following is a LOGICAL error rather than a syntax or run-time error?

Q12

Given list1 = [10, 20] and list2 = [10, 20], which statement evaluates to True?

NCERT solutions & previous-year questions

Step-by-step model answers — tap a question to reveal the full solution.

NCERT questions 6

1 Which of the following can be used as identifiers (variable names) in Python, and why? Serial_no. , 1st_Room , Hundred$ , Total Marks , total_marks , _Percentage , True , PercentageIdentifiers and keywords

An identifier may contain only letters, digits and the underscore, must not start with a digit, and must not be a keyword. Checking every candidate with Python itself — the first flag is isidentifier() (right shape?) and the second is iskeyword() (reserved?):

import keyword

print("Serial_no.  ->", "Serial_no.".isidentifier(), keyword.iskeyword("Serial_no."))
print("1st_Room    ->", "1st_Room".isidentifier(), keyword.iskeyword("1st_Room"))
print("Hundred$    ->", "Hundred$".isidentifier(), keyword.iskeyword("Hundred$"))
print("Total Marks ->", "Total Marks".isidentifier(), keyword.iskeyword("Total Marks"))
print("total_marks ->", "total_marks".isidentifier(), keyword.iskeyword("total_marks"))
print("_Percentage ->", "_Percentage".isidentifier(), keyword.iskeyword("_Percentage"))
print("True        ->", "True".isidentifier(), keyword.iskeyword("True"))
print("Percentage  ->", "Percentage".isidentifier(), keyword.iskeyword("Percentage"))
Serial_no.  -> False False
1st_Room    -> False False
Hundred$    -> False False
Total Marks -> False False
total_marks -> True False
_Percentage -> True False
True        -> True True
Percentage  -> True False

A name is usable only when the first flag is True and the second is False. On that rule, only total_marks, _Percentage and Percentage survive.

NameValid?Reason
Serial_no.NoContains a full stop. The dot is the attribute operator, so Python reads this as Serial_no dot something.
1st_RoomNoBegins with a digit.
Hundred$No$ is not allowed in an identifier.
Total MarksNoContains a space; Python sees two separate tokens.
total_marksYesLetters and underscore only.
_PercentageYesA leading underscore is permitted.
TrueNoReserved keyword. "True".isidentifier() is True (right shape) but keyword.iskeyword("True") is also True, so it cannot be used.
PercentageYesLetters only. Note it is different from percentage.
2 Write the corresponding Python assignment statements: (a) Assign 10 to length and 20 to breadth. (b) Assign the average of length and breadth to a variable. (c) Assign a list containing 'Paper', 'Gel Pen' and 'Eraser' to stationery. (d) Assign 'Mohandas', 'Karamchand' and 'Gandhi' to first, middle and last. (e) Assign the concatenation of first, middle and last to fullname, with blank spaces in between.Variables and assignment
length = 10
breadth = 20
avg = (length + breadth) / 2
stationery = ['Paper', 'Gel Pen', 'Eraser']
first, middle, last = 'Mohandas', 'Karamchand', 'Gandhi'
fullname = first + ' ' + middle + ' ' + last

print(length, breadth)
print(avg)
print(stationery)
print(first, middle, last)
print(fullname)
print(len(fullname))
10 20
15.0
['Paper', 'Gel Pen', 'Eraser']
Mohandas Karamchand Gandhi
Mohandas Karamchand Gandhi
26

Points to note. (b) The brackets around length + breadth are essential; without them / would run first and give 10 + 10.0 = 20.0 instead of 15.0. The result is 15.0, a float, because / always returns a float. (d) uses multiple assignment, which is shorter than three separate lines and evaluates the whole right side first. (e) The ' ' pieces must be added explicitly: first + middle + last alone would give MohandasKaramchandGandhi. len(fullname) is 26 — 24 letters plus the 2 spaces — which confirms the spaces went in.

3 Write logical expressions in Python for the following statements and evaluate them, assuming num1 = 5, num2 = 10, num3 = 24, first = 'Mohandas', middle = 'Karamchand', last = 'Gandhi', stationery = []. (a) The sum of 20 and -10 is less than 12. (b) num3 is not more than 24. (c) 6.75 is between the values of num1 and num2. (d) The string 'middle' is larger than 'first' and smaller than 'last'. (e) The list stationery is empty.Relational and logical operators
num1, num2, num3 = 5, 10, 24
first, middle, last = 'Mohandas', 'Karamchand', 'Gandhi'
stationery = []

print("(a)", 20 + (-10) < 12)
print("(b)", num3 <= 24)
print("(c)", num1 < 6.75 < num2)
print("(d)", first < middle < last)
print("(e)", stationery == [])
print("(e alt)", len(stationery) == 0)
(a) True
(b) True
(c) True
(d) False
(e) True
(e alt) True

(a) 20 + (-10) is 10, and 10 < 12, so True.

(b) "not more than 24" means "at most 24", i.e. num3 <= 24. With num3 exactly 24 this is True. Writing not (num3 > 24) is equally correct and gives the same answer.

(c) Python allows the chained form num1 < 6.75 < num2, which reads like maths; it is the same as num1 < 6.75 and 6.75 < num2. With 5 and 10 it is True.

(d) The expression is first < middle < last, and it evaluates to False. Strings compare character by character using Unicode order, and 'M' (of Mohandas) comes after 'K' (of Karamchand), so 'Mohandas' < 'Karamchand' is already False and the chain short-circuits. The expression is written correctly; the given values simply do not satisfy it.

(e) stationery == [] is the direct translation. len(stationery) == 0 and even not stationery also work, since an empty list is falsy.

4 Add a pair of parentheses to each expression so that it evaluates to True: (a) 0 == 1 == 2 (b) 2 + 3 == 4 + 5 == 7 (c) 1 4Operator precedence and chained comparison

First, why each one is False as written. Python treats a == b == c as a chained comparison, meaning a == b and b == c. Adding brackets breaks the chain into a single comparison, which changes the meaning completely. Also remember that True is 1 and False is 0 in arithmetic.

print("(a) 0 == (1 == 2)          ->", 0 == (1 == 2))
print("    (0 == 1) == 2          ->", (0 == 1) == 2)
print("(b) 2 + (3 == 4) + 5 == 7  ->", 2 + (3 == 4) + 5 == 7)
print("(c) (1 < -1) == (3 > 4)    ->", (1 < -1) == (3 > 4))

print()
print("originals:")
print("0 == 1 == 2          ->", 0 == 1 == 2)
print("2 + 3 == 4 + 5 == 7  ->", 2 + 3 == 4 + 5 == 7)
print("1 < -1 == 3 > 4      ->", 1 < -1 == 3 > 4)
(a) 0 == (1 == 2)          -> True
    (0 == 1) == 2          -> False
(b) 2 + (3 == 4) + 5 == 7  -> True
(c) (1 < -1) == (3 > 4)    -> True

originals:
0 == 1 == 2          -> False
2 + 3 == 4 + 5 == 7  -> False
1 < -1 == 3 > 4      -> False

(a) 0 == (1 == 2). The inner 1 == 2 gives False, which is 0 in numeric terms, and 0 == False is True. Note the other placement, (0 == 1) == 2, gives False — it becomes False == 2, i.e. 0 == 2.

(b) 2 + (3 == 4) + 5 == 7. The bracket forces 3 == 4 to be evaluated first, giving False = 0. The left side is then 2 + 0 + 5 = 7, and 7 == 7 is True. Only one == remains outside brackets, so there is no chaining.

(c) (1 < -1) == (3 > 4). Both brackets give False, and False == False is True.

5 Give the output of the following, where num1 = 4, num2 = 3 and num3 = 2. (a) num1 += num2 + num3 (b) num1 = num1 ** (num2 + num3) (c) num1 **= num2 + num3 (d) num1 = '5' + '3' (e) 4.00 / (2.0 + 2.0) (f) 2 + 9 * ((3 * 12) - 8) / 10 (g) 24 // 4 // 2 (h) float(10) (i) int('3.14') (j) 'Bye' == 'BYE' (k) 10 != 9 and 20 >= 20 (l) not 10 > 5Operators and expression evaluation
num1, num2, num3 = 4, 3, 2

n = num1; n += num2 + num3;        print("(a)", n)
n = num1; n = n ** (num2 + num3);  print("(b)", n)
n = num1; n **= num2 + num3;       print("(c)", n)
n = '5' + '3';                     print("(d)", n, type(n))
print("(e)", 4.00 / (2.0 + 2.0))
print("(f)", 2 + 9 * ((3 * 12) - 8) / 10)
print("(g)", 24 // 4 // 2)
print("(h)", float(10))
print("(j)", 'Bye' == 'BYE')
print("(k)", 10 != 9 and 20 >= 20)
print("(l)", not 10 > 5)
(a) 9
(b) 1024
(c) 1024
(d) 53 
(e) 1.0
(f) 27.2
(g) 3
(h) 10.0
(j) False
(k) True
(l) False

Part (i) is left out of that program on purpose, because it does not produce an output at all — it stops the program:

print(int('3.14'))
Traceback (most recent call last):
  File "C:\pytmp\n5_i.py", line 1, in 
    print(int('3.14'))
          ~~~^^^^^^^^
ValueError: invalid literal for int() with base 10: '3.14'

Working. (a) The right side is computed first: 3 + 2 = 5, then 4 + 5 = 9. (b) and (c) are the same operation written two ways: 3 + 2 = 5, then 4 ** 5 = 1024 — the augmented form **= also evaluates its whole right side before exponentiating. (d) + on two strings joins them, so the answer is the string '53', not 8. (e) 2.0 + 2.0 = 4.0, and 4.00 / 4.0 = 1.0, a float. (f) (3 x 12) - 8 = 28; 9 x 28 = 252; 252 / 10 = 25.2; 2 + 25.2 = 27.2. (g) // is left-associative: (24 // 4) // 2 = 6 // 2 = 3. (h) float(10) is 10.0. (i) A run-time error, not an output: int() will not parse a decimal point. The workaround is int(float('3.14')), which gives 3. (j) String comparison is case sensitive, so 'Bye' and 'BYE' are different. (k) 10 != 9 is True and 20 >= 20 is True, so True and True is True. (l) 10 > 5 is True, and not True is False.

6 Categorise each of the following as a syntax error, a logical error or a run-time error, and justify: (a) dividing 25 by a variable holding 0 (b) print(num1 + num2 with the closing bracket missing (c) computing an average as num1 + num2 / 2 (d) int(input()) when the user types abcErrors - syntax, logical and run-time

(a) Run-time error. The code is grammatically perfect; the failure only happens when the values arrive.

num1 = 25
num2 = 0
print(num1 / num2)
Traceback (most recent call last):
  File "C:\pytmp\ncert6a.py", line 3, in 
    print(num1 / num2)
          ~~~~~^~~~~~
ZeroDivisionError: division by zero

(b) Syntax error. The grammar is broken, so the interpreter refuses to run even the first line.

num1 = 25
num2 = 10
print(num1 + num2
  File "C:\pytmp\ncert6b.py", line 3
    print(num1 + num2
         ^
SyntaxError: '(' was never closed

(c) Logical error. It runs cleanly and prints a wrong number, so Python says nothing at all.

num1 = 25
num2 = 10
avg = num1 + num2 / 2
print("Average =", avg)
Average = 30.0

The average of 25 and 10 is 17.5, but / outranks +, so Python computed 25 + (10/2) = 30.0. The fix is avg = (num1 + num2) / 2. Nothing but checking the answer by hand would have caught this.

(d) Run-time error. int() is a valid call and the program starts normally — the prompt is even printed — but the text supplied cannot be converted.

num = int(input("Enter a number: "))
print(100 / num)
Enter a number: Traceback (most recent call last):
  File "C:\pytmp\ncert6d.py", line 1, in 
    num = int(input("Enter a number: "))
ValueError: invalid literal for int() with base 10: 'abc'

The rule for the exam: if the interpreter cannot even start, it is a syntax error. If it starts and then stops with a Traceback, it is a run-time error. If it finishes happily but the answer is wrong, it is a logical error.

Previous-year board questions 4

Q1 Rewrite the following code after removing all the errors. Underline each correction made.Num = int(input("Enter a number"))if Num % 2 = 0 print("Even")else print("Odd) 2023-24 (board pattern)

There are four errors. Running the code as given, Python reports the last one first, because an unterminated string stops the whole file from being tokenised:

  File "C:\pytmp\pyq1_bad.py", line 5
    print("Odd)
          ^
SyntaxError: unterminated string literal (detected at line 5)

The four corrections:

  1. = changed to == in the condition. A single = is assignment, not comparison, and cannot appear inside an if.
  2. Colon added after the if condition.
  3. Colon added after else.
  4. Closing quote added to "Odd".

Corrected program (the four changed places are ==, the colon after 0, the colon after else, and the closing quote after Odd):

Num = int(input("Enter a number: "))
if Num % 2 == 0:
    print("Even")
else:
    print("Odd")

Two real runs:

Enter a number: 7
Odd
Enter a number: 10
Even

Note that int(...) around the input() was already correct in the question and must be kept — without it, Num would be a string and Num % 2 would fail with a TypeError.

Q2 Evaluate the following expressions, showing the order in which the operators are applied. Given a = 10, b = 3, c = 2.(i) a + b * c ** 2 - a // b(ii) a % b + b % c * 2(iii) not (a > b) or (c (iv) a / b // c(v) (a > b) + (b > c) 2024-25 (board pattern)
a, b, c = 10, 3, 2
print("(i)  ", a + b * c ** 2 - a // b)
print("(ii) ", a % b + b % c * 2)
print("(iii)", not (a > b) or (c < b and a != 10))
print("(iv) ", a / b // c)
print("(v)  ", (a > b) + (b > c))
(i)   19
(ii)  3
(iii) False
(iv)  1.0
(v)   2

(i) = 19. ** first: c ** 2 = 4. Then the * and // level, left to right: b * 4 = 12, and a // b = 10 // 3 = 3. Then + and -: 10 + 12 - 3 = 19.

(ii) = 3. The % and * level runs left to right: a % b = 10 % 3 = 1; b % c = 3 % 2 = 1; then 1 * 2 = 2. Finally 1 + 2 = 3. The common slip is to add first and multiply afterwards, i.e. to read it as (a % b + b % c) * 2, which gives 4.

(iii) = False. Brackets first: a > b is True, c < b is True, a != 10 is False. Then not True = False, and True and False = False. Finally False or False = False.

(iv) = 1.0. / and // share a precedence level and run left to right: a / b = 10/3 = 3.3333..., then 3.3333... // 2 = 1.0. The answer is a float, not the integer 1, because one operand was already a float. Doing a / (b // c) instead would give 10.0.

(v) = 2. Both comparisons are True, and in Python True is the integer 1, so True + True = 2. This is the standard trick for counting how many conditions held.

Q3 (a) Differentiate between the == operator and the is operator with a suitable example. (b) What is meant by mutable and immutable data types? Give one example of each and show, using id(), how they differ. 2024-25 (board pattern)

(a) == versus is. == asks whether two objects hold the same value. is asks whether two names refer to the very same object in memory, and is exactly equivalent to comparing id() values. Two objects can be equal without being identical.

(b) Mutable and immutable. An immutable object cannot be changed after it is created — any operation that appears to change it actually builds a new object and moves the name to it. Immutable types: int, float, complex, bool, str, tuple, None. A mutable object can be edited in place, keeping the same identity. Mutable types: list, dict.

Combined demonstration:

list1 = [10, 20, 30]
list2 = [10, 20, 30]
list3 = list1

print("list1 == list2 :", list1 == list2)
print("list1 is list2 :", list1 is list2)
print("list1 is list3 :", list1 is list3)

list3[0] = 99
print("after list3[0] = 99 ->")
print("list1 =", list1)
print("list2 =", list2)

str1 = "UPI"
print("id(str1) before:", id(str1))
str1 += " Pay"
print("str1 =", str1, "| id after:", id(str1))
list1 == list2 : True
list1 is list2 : False
list1 is list3 : True
after list3[0] = 99 ->
list1 = [99, 20, 30]
list2 = [10, 20, 30]
id(str1) before: 2553941746352
str1 = UPI Pay | id after: 2553941748080

Reading the output. list1 == list2 is True (same contents) but list1 is list2 is False (two separate objects). list3 = list1 created an alias, not a copy, so list1 is list3 is True — and changing list3[0] changed list1 too, while the independent list2 was untouched. That is mutability in action: the list object itself was edited.

The string shows the opposite. str1 += " Pay" produced a different id, because a str cannot be altered; Python built a fresh string and rebound the name. (The exact id numbers differ on every run; only the fact that one changed and the other did not is meaningful.)

Q4 Write a Python program that accepts the name of a student and marks in Physics, Chemistry and Maths from the user, then displays the total marks out of 300, the percentage rounded to two decimal places, and whether the student has passed (33% or above). 2025-26 (board pattern)

The whole marks of this question sit in one place: input() returns a string, so every numeric input must be wrapped in int(). Without that, p + c + m would join the three strings instead of adding them.

name = input("Enter student name : ")
print(name)                      # echo, so this transcript matches your screen
p = int(input("Physics marks      : "))
print(p)
c = int(input("Chemistry marks    : "))
print(c)
m = int(input("Maths marks        : "))
print(m)

total = p + c + m
percent = total / 3

print("--------------------------------")
print("Student    :", name)
print("Total      :", total, "/ 300")
print("Percentage :", round(percent, 2))
print("Passed     :", percent >= 33)

Sample run (typed values: Aarav Mehta, 78, 85, 91):

Enter student name : Aarav Mehta
Physics marks      : 78
Chemistry marks    : 85
Maths marks        : 91
--------------------------------
Student    : Aarav Mehta
Total      : 254 / 300
Percentage : 84.67
Passed     : True

Points that earn marks. The name is left as a string — it must not be converted. The marks are converted with int() at the moment of reading, which is safer than converting later. Because the paper is out of 300, total / 3 is already the percentage; writing total / 300 * 100 gives the same 84.66666666666667 here and is equally acceptable. round(percent, 2) turns 84.66666666666667 into 84.67 — without it, the raw float prints all its digits. Finally, percent >= 33 is itself an expression of type bool, so it can be printed directly.

If int() is omitted: the three inputs 78, 85 and 91 would give total = the string '788591', and the next line total / 3 would stop the program with TypeError: unsupported operand type(s) for /: 'str' and 'int'.

Part of Priodemy for School

Interactive CBSE lessons, Class 8–12 — free with every school on Priodemy EduSuite. Explore more chapters and labs on the Priodemy for School hub.

Ask AI