Class 10Computer ScienceFull chapter

Python Programming

Everything the Class 10 syllabus asks of Python, in one place — if / elif / else, the while and for loops, lists and strings, and the short programs examiners set again and again. Every snippet comes with the output it actually produces, so you can dry-run it the way you must in the paper.

Variables, Data Types and Reading Input

Quick answer A quick, exam-shaped recap: what a variable is, the naming rules examiners ask for, the four data types you must name, and why input() always hands you a string.

Python is a high-level programming language — a language written in words close to English, which the computer translates into machine instructions for you. Everything in this chapter follows Python 3. If you meet older code that writes print "Hello" without brackets, that is Python 2 and it will not run in Python 3, so do not copy that style into your answer sheet.

A variable is a named location in memory that stores a value. You create one simply by assigning to it with the assignment operator =. There is no separate declaration line in Python: the moment you assign, the variable exists and its type is decided by the value you gave it.

name = "Ananya"
roll = 21
fee = 1250.50
passed = True

The name of a variable is called an identifier, and the rules for a valid identifier are asked for in exactly this form. An identifier may contain letters, digits and the underscore. It must not begin with a digit. It must not contain a space or a special symbol such as @, - or #. It must not be a keyword — a word already reserved by Python, such as if, else, for, while, True or break. Finally, identifiers are case sensitive, so Marks, marks and MARKS are three different variables. A name such as total_fee is valid; total fee, 2ndterm and class are not.

The data type of a value tells Python what kind of data it is and what may be done with it. Four types cover almost every question at this level, and a fifth (the list) has a section of its own.

  • int — a whole number, positive, negative or zero: 21, -7, 0.
  • float — a number with a decimal point: 1250.50, 3.0.
  • str — a string, that is text in quotes: "Ananya", '10'.
  • bool — a Boolean value, only True or False, written with a capital letter.

The built-in function type() reports the type: print(type(fee)) shows that fee is a float. Python is dynamically typed, which means the type follows the value — assigning roll = "twenty one" later would make roll a string.

Output is produced by print(). When you pass several items separated by commas, Python prints them in order with a single space between them, then moves to a new line.

Input is read by input(), and here is the point examiners test most: input() always returns a string, even when the user types digits. To calculate with it you must convert, using int() for whole numbers or float() for decimals. Forgetting the conversion is why 2 and 3 sometimes join into "23" instead of adding to 5.

price = int(input("Enter price in rupees: "))
qty = int(input("Enter quantity: "))
print("Total payable =", price * qty)

The arithmetic operators are +, -, *, /, //, % and **. Two of them are examined constantly: / is true division and always gives a float, so 17 / 5 is 3.4, while // is floor division and gives the whole part, so 17 // 5 is 3. The remainder operator % gives 17 % 5 as 2, and it is the standard way to test divisibility: a number n is even when n % 2 == 0. Exponentiation ** gives 2 ** 3 as 8.

Anything after a # on a line is a comment; Python ignores it. Comments do not earn marks by themselves, but one line explaining a tricky step reads well and costs nothing.

Assignment name = value Creates the variable; no separate declaration line exists in Python.
Data types int, float, str, bool 21, 1250.50, "Ananya", True — the four to name in a definition answer.
Reading a number n = int(input("Enter n: ")) input() returns a string; int() converts it.
Division pair 17 / 5 = 3.4 , 17 // 5 = 3 / is true division and always float; // is floor division.
Even test n % 2 == 0 % is the remainder operator; also used for divisibility by any number.
Remember
  • A variable is a named memory location; assignment with = creates it and its type follows the value.
  • Identifier rules: letters, digits and underscore only; no leading digit, no spaces, no keywords; case sensitive.
  • The four basic types to name in an answer are int, float, str and bool; type() reports the type.
  • input() always returns a string — wrap it in int() or float() before doing arithmetic.
  • / gives a float (17 / 5 is 3.4), // gives the whole part (17 // 5 is 3), % gives the remainder.
  • n % 2 == 0 is the standard test for an even number.

Decision Making: if, elif, else and Indentation

Quick answer How Python chooses between paths, why the colon and the indentation are part of the grammar rather than decoration, and the order in which an elif ladder must be written.

A program that always does the same thing is of little use. Decision making lets a program test a condition — an expression that evaluates to True or False — and run one block of statements or another.

Conditions are built from the relational operators: == (equal to), != (not equal to), >, <, >= and <=. Two or more conditions are combined with the logical operators and (true only when both sides are true), or (true when at least one side is true) and not (reverses a condition). Note the double equals sign in ==. A single = is assignment, not comparison, and putting it in a condition is an error you will meet again at the end of this chapter.

The simplest form is if alone:

marks = int(input("Enter marks: "))
if marks >= 33:
    print("Pass")

Two details in those three lines are syntax, not style. First, the if header ends with a colon. Second, the statements controlled by the if are indented — pushed in from the left margin. Most other languages mark a block with braces and treat indentation as a courtesy to the reader; Python has no braces, so the indentation itself defines the block. Miss the colon and Python reports a SyntaxError; indent wrongly and it reports an IndentationError.

The accepted convention is four spaces for each level, and every line of one block must be indented by the same amount. Do not mix tabs and spaces: editors differ in how wide they draw a tab — some show four columns, others eight — so code that looks aligned on one machine can be rejected on another. Set your editor to insert spaces when you press Tab, or simply press the space bar four times.

Adding else supplies the alternative path. The else keyword takes no condition, and it is written at the same indentation as its if:

n = int(input("Enter a number: "))
if n % 2 == 0:
    print(n, "is even")
else:
    print(n, "is odd")

When there are more than two paths, use elif — short for else if. You may write as many elif branches as you need, and a final else is optional. Python tests the conditions from the top downwards, stops at the first one that is true, runs that block and skips every remaining branch. That single sentence is what a full-mark answer on elif contains.

marks = int(input("Enter marks out of 100: "))

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

Because the first true branch wins, the order of the tests matters. If you had written marks >= 33 first, then 95 marks would satisfy it and print "Grade D", and no later branch would ever run. When the boundaries overlap like this, arrange them from the strictest to the loosest.

The classic examination program for this topic is the largest of three numbers, and it can be answered with a single ladder:

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

if a >= b and a >= c:
    print("Largest =", a)
elif b >= a and b >= c:
    print("Largest =", b)
else:
    print("Largest =", c)

Using >= rather than > matters: if all three numbers are equal, > would fall through every branch to the else and still be right by luck, but with two equal largest values a strict > test can miss. Write >= and the answer is safe in every case.

An if may also be placed inside another if; this is a nested if, and the inner block is simply indented one level further. Prefer an elif ladder where you can — it is shorter and much easier to mark.

if header if condition: Colon ends the header; the controlled statements are indented below it.
Compare vs assign == compares , = assigns A single = inside an if header is a SyntaxError in Python.
Multi-way choice if ... elif ... else: First true branch runs; else is optional and carries no condition.
Logical operators and , or , not and needs both true; or needs at least one; not reverses.
Block rule 4 spaces = one level Wrong indentation raises IndentationError, not a wrong answer.
Remember
  • A condition evaluates to True or False using ==, !=, &gt;, &lt;, &gt;= and &lt;=, combined with and, or and not.
  • Every if / elif / else header ends with a colon, and the block below it must be indented — indentation is Python's syntax for a block.
  • Use four spaces per level and never mix tabs with spaces; editors draw tabs at different widths.
  • In an if / elif / else ladder only the first true branch runs; every later branch is skipped.
  • Order overlapping conditions from strictest to loosest, or the loose one swallows every case.
  • else takes no condition and sits at the same indentation as its if.

The while Loop

Quick answer A while loop repeats as long as its condition stays true. Learn its three moving parts, why a missing update creates an infinite loop, and the accumulator pattern behind sum and factorial.

A loop repeats a block of statements. The while loop repeats it as long as a condition remains true, and it is the right choice when you do not know in advance how many repetitions are needed.

Every correct while loop has three moving parts, and naming them earns marks in a theory question:

  1. Initialisation — the control variable is given a starting value before the loop.
  2. Test — the condition in the while header, checked before every repetition.
  3. Update — a statement inside the body that moves the control variable towards making the condition false.
i = 1                 # initialisation
while i <= 5:         # test
    print(i, end=" ")
    i = i + 1         # update
print()

The output is 1 2 3 4 5. The end=" " argument tells print to finish with a space instead of a new line, so the numbers appear on one line; the bare print() afterwards moves to the next line.

Because the condition is tested before the body runs, while is called an entry-controlled loop, and the body may run zero times. If i started at 9 in the loop above, nothing at all would be printed. Examiners like this point, so state it plainly.

Remove the update line and i stays 1 for ever, the condition stays true, and you have an infinite loop. In most environments pressing Ctrl+C interrupts a runaway program, but the real cure is to check, before you write the closing line of the body, that something inside it changes the variable the condition depends on.

Two patterns cover nearly every while question in the paper. The first is the accumulator: a variable set to a starting value outside the loop, then built up inside it. For a sum the accumulator starts at 0, because adding 0 changes nothing.

n = int(input("Enter n: "))
total = 0
i = 1
while i <= n:
    total = total + i
    i = i + 1
print("Sum of first", n, "natural numbers =", total)

For a product the accumulator starts at 1, because multiplying by 1 changes nothing — starting it at 0 would make every answer 0, a very common slip.

n = int(input("Enter a number: "))
fact = 1
i = 1
while i <= n:
    fact = fact * i
    i = i + 1
print("Factorial of", n, "is", fact)

Trace it for n = 4, which is exactly what a dry-run question asks you to write out:

  • Before the loop: fact = 1, i = 1.
  • Pass 1: 1 <= 4 is true, fact = 1 * 1 = 1, i becomes 2.
  • Pass 2: fact = 1 * 2 = 2, i becomes 3.
  • Pass 3: fact = 2 * 3 = 6, i becomes 4.
  • Pass 4: fact = 6 * 4 = 24, i becomes 5.
  • Test: 5 <= 4 is false, the loop ends, and 24 is printed.

Notice that for n = 0 the body never runs and the answer printed is 1, which is the correct value of 0 factorial.

The second pattern is the sentinel-controlled loop, where the user keeps entering values until a chosen stopping value is typed. Here the number of repetitions is genuinely unknown, so while is the natural choice.

total = 0
value = int(input("Enter an amount in rupees (0 to stop): "))
while value != 0:
    total = total + value
    value = int(input("Enter an amount in rupees (0 to stop): "))
print("Total =", total)

The input statement appears twice on purpose: once before the loop so the first test has something to examine, and once at the end of the body so the next test has a fresh value. That repeated line is the update.

while header while condition: Colon, then an indented body — the same block rule as if.
Counting up i = 1 ... i = i + 1 Initialise outside, update inside; forget the update and it never ends.
Sum accumulator total = total + value Set total = 0 before the loop.
Factorial accumulator fact = fact * i Set fact = 1 before the loop; 0 would destroy every product.
Loop type entry-controlled Test happens before each pass, so 0 or more repetitions.
Remember
  • while repeats while its condition is true; use it when the number of repetitions is not known in advance.
  • Three parts: initialise before the loop, test in the header, update inside the body.
  • while is entry-controlled — the condition is tested first, so the body may run zero times.
  • A missing or wrong update gives an infinite loop; Ctrl+C interrupts it in most environments.
  • A sum accumulator starts at 0; a product (factorial) accumulator starts at 1, never 0.
  • In a sentinel loop the input statement appears twice: once before the loop and once at the end of the body.

The for Loop, range(), break, continue and Nesting

Quick answer The for loop walks through a sequence. range() manufactures that sequence in three forms, and its stop value is always excluded — the single fact behind most output questions.

The for loop repeats its body once for each item of a sequence. The sequence can be a range of numbers, a list or a string, and the loop variable takes each item in turn. Use for when the number of repetitions is known or countable; use while when it is not.

The sequence of numbers usually comes from the built-in function range(), which has three forms.

  • range(stop) — counts from 0 up to but not including stop. range(5) gives 0, 1, 2, 3, 4.
  • range(start, stop) — counts from start up to but not including stop. range(2, 6) gives 2, 3, 4, 5.
  • range(start, stop, step) — counts from start, adding step each time, stopping before stop. range(1, 10, 2) gives 1, 3, 5, 7, 9.

Learn one sentence and half the output questions in this chapter answer themselves: the stop value is always excluded, and the start value is always included. So range(1, 5) produces four numbers, not five, and the count of values in range(a, b) is b - a.

The step may be negative, which counts downwards. range(5, 0, -1) gives 5, 4, 3, 2, 1 — again the stop value 0 is left out. range(10, 0, -2) gives 10, 8, 6, 4, 2. If the start has already passed the stop in the direction of travel, the range is empty and the loop body never runs at all: range(5, 1) produces nothing, because the default step of +1 can never reach downwards.

The multiplication table is the standard for question:

n = int(input("Enter a number: "))
for i in range(1, 11):
    print(n, "x", i, "=", n * i)

The 11 is deliberate. To run from 1 to 10 inclusive you must write range(1, 11); writing range(1, 10) stops at 9 and leaves the last row out. Whenever a question says "from 1 to n", the correct range is range(1, n + 1).

Two keywords change the normal flow. break leaves the loop immediately, skipping the remaining items altogether. continue skips the rest of the current pass only and jumps straight to the next item.

for i in range(1, 11):
    if i == 5:
        break
    print(i, end=" ")

That prints 1 2 3 4 and then stops for good. Replace break with continue and the output becomes 1 2 3 4 6 7 8 9 10 — only the value 5 is missed, and the loop carries on. A neat use of continue is printing the odd numbers:

for i in range(1, 11):
    if i % 2 == 0:
        continue
    print(i, end=" ")

which prints 1 3 5 7 9.

A loop written inside the body of another loop is a nested loop. The rule to state in an answer is that the inner loop completes all its repetitions for every single pass of the outer loop. If the outer loop runs 3 times and the inner loop runs 4 times, the innermost statement runs 3 × 4 = 12 times.

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

The output has three lines: 1 2 3, then 2 4 6, then 3 6 9. Notice where the bare print() sits — indented to the outer loop, not the inner one — so it runs once per row and ends the line.

Pattern printing uses the same idea with the inner range depending on the outer variable:

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

This prints one star, then two, then three, then four, on four lines. One last caution: a break written inside the inner loop leaves only the inner loop; the outer loop continues with its next value.

for header for var in range(...): The loop variable takes each value of the sequence in turn.
One argument range(5) 0 1 2 3 4 — starts at 0, stop excluded.
Two arguments range(2, 6) 2 3 4 5 — four values, because 6 - 2 = 4.
Three arguments range(5, 0, -1) 5 4 3 2 1 — a negative step counts downwards.
1 to n inclusive range(1, n + 1) The +1 that prevents the commonest off-by-one error.
Remember
  • for repeats once per item of a sequence — a range, a list or a string.
  • range() has three forms: range(stop), range(start, stop) and range(start, stop, step).
  • The stop value is always excluded and the start included, so range(a, b) yields b - a values.
  • For 1 to n inclusive write range(1, n + 1); a negative step counts down, as in range(5, 0, -1).
  • break leaves the loop at once; continue skips only the rest of the current pass.
  • In a nested loop the inner loop finishes completely for every pass of the outer loop, giving outer × inner repetitions.

Lists: Indexing, Slicing and Methods

Quick answer A list stores many values under one name. Learn indexing including negative indices, slicing, len(), the six methods on the syllabus, and how to traverse a list with a for loop.

A list is an ordered collection of values stored under one name. It is written inside square brackets with the items separated by commas, and it may hold items of different types, though in exam questions it usually holds numbers or strings.

marks = [78, 85, 62, 91, 55]
names = ["Ananya", "Rahul", "Meera"]
empty = []

Each item has a position number called its index. Indexing starts at 0, so the valid indices of a list of five items are 0, 1, 2, 3 and 4 — the last index is always len - 1. Python also supports negative indexing, which counts from the right: -1 is the last item, -2 the second last, and so on. This is why marks[-1] is the neat way to reach the last item without knowing the length.

marks = [78, 85, 62, 91, 55]
print(marks[0])    # 78
print(marks[3])    # 91
print(marks[-1])   # 55
print(marks[-2])   # 91
print(len(marks))  # 5

Asking for an index that does not exist, such as marks[5] here, raises an IndexError. The function len() returns the number of items, and it is the safe way to find the last index: marks[len(marks) - 1].

A slice takes a part of the list and gives back a new list. The form is list[start:stop], and — exactly as with range() — the stop position is excluded. Omitting start means "from the beginning"; omitting stop means "to the end".

marks = [78, 85, 62, 91, 55]
print(marks[1:4])   # [85, 62, 91]
print(marks[:3])    # [78, 85, 62]
print(marks[2:])    # [62, 91, 55]
print(marks[-2:])   # [91, 55]

Unlike a string, a list is mutable — it can be changed in place. marks[0] = 90 replaces the first item, and the methods below change the list itself rather than returning a changed copy.

  • append(item) — adds one item at the end.
  • insert(pos, item) — inserts the item at position pos, shifting the rest to the right.
  • remove(value) — deletes the first occurrence of that value; raises a ValueError if the value is not present.
  • pop() — removes and returns the last item; pop(index) removes and returns the item at that index.
  • sort() — rearranges the list into ascending order in place; sort(reverse=True) gives descending order.
  • reverse() — reverses the order of the items in place.
fees = [1200, 1500, 900]
fees.append(2000)      # [1200, 1500, 900, 2000]
fees.insert(1, 1000)   # [1200, 1000, 1500, 900, 2000]
fees.remove(900)       # [1200, 1000, 1500, 2000]
x = fees.pop()         # x = 2000, fees = [1200, 1000, 1500]
y = fees.pop(0)        # y = 1200, fees = [1000, 1500]
fees.sort()            # [1000, 1500]
fees.reverse()         # [1500, 1000]

Three distinctions are worth memorising. First, remove() takes a value while pop() takes a position. Second, append() adds a single item: starting from nums = [1, 2, 3], the call nums.append([4, 5]) puts the whole small list in as one item, giving [1, 2, 3, [4, 5]]. Third, sort() and reverse() return None, so writing marks = marks.sort() throws the list away and leaves marks holding None. Call marks.sort() on its own line.

Traversal means visiting every item. The direct form loops over the list itself; the indexed form is used when you also need the position.

marks = [78, 85, 62, 91, 55]

for m in marks:
    print(m, end=" ")
print()

for i in range(len(marks)):
    print("Index", i, "holds", marks[i])

The standard traversal question is finding the largest value. Set the answer to the first item, then improve it as you walk through the rest:

marks = [78, 85, 62, 91, 55]
largest = marks[0]
for m in marks:
    if m > largest:
        largest = m
print("Largest =", largest)

Start largest at marks[0], never at 0 — a list of negative values would then report 0, which is not even in the list. The same shape with < finds the smallest, and adding total = total + m finds the sum.

Create and measure marks = [78, 85, 62] ; len(marks) len gives the count; the last index is len - 1.
Last item marks[-1] Negative indexing counts from the right; marks[5] on a 5-item list is an IndexError.
Slice marks[1:4] Items at index 1, 2 and 3 — the stop index 4 is excluded.
Add and remove append(x) , insert(p, x) , remove(v) , pop(i) remove takes a value, pop takes a position and returns the item.
Reorder marks.sort() , marks.reverse() Both change the list in place and return None.
Remember
  • A list is an ordered, mutable collection written in square brackets; items may be of mixed types.
  • Indexing starts at 0, so the last index is len - 1; negative indices count from the right, with -1 as the last item.
  • A slice list[start:stop] returns a new list and excludes the stop position.
  • append adds one item at the end, insert places it at a position, remove takes a value, pop takes a position and returns the item.
  • sort() and reverse() change the list in place and return None — never write marks = marks.sort().
  • To find the largest, start from list[0] and compare, not from 0.

Strings: Indexing, Slicing and Traversal

Quick answer A string is a sequence of characters, so indexing and slicing work exactly as they do on lists — with one crucial difference: a string cannot be changed in place.

A string is a sequence of characters enclosed in quotes. Single and double quotes are both accepted and mean the same thing; choose the pair that the text itself does not contain, so "Ananya's marks" is easiest with double quotes.

Because a string is a sequence, everything you learned about list positions applies. Indexing starts at 0, the last character is at index len - 1, and negative indices count from the right with -1 as the last character. The space is a character too and occupies its own index.

s = "Computer"
print(len(s))    # 8
print(s[0])      # C
print(s[3])      # p
print(s[-1])     # r
print(s[2:5])    # mpu
print(s[:4])     # Comp
print(s[4:])     # uter

Slicing follows the same exclusive-stop rule: s[2:5] gives the characters at indices 2, 3 and 4. The slice s[::-1] uses a step of −1 and therefore produces the whole string backwards, which is the shortest way to reverse a string.

The one big difference from a list is that a string is immutable — once created it cannot be changed. Writing s[0] = "R" raises a TypeError. To "change" a string you build a new one and assign it back, and that is why string methods hand you a fresh string rather than editing the original.

Two operators are examined by name. Concatenation with + joins two strings end to end. Both operands must be strings — "Roll " + 21 is a TypeError, and you must write "Roll " + str(21). Repetition with * repeats a string a whole number of times, so "ab" * 3 is "ababab"; here one operand must be a string and the other an integer.

first = "Priya"
last = "Sharma"
full = first + " " + last
print(full)          # Priya Sharma
print("-" * 20)      # a line of 20 hyphens
print(len(full))     # 12

Note the deliberate " " in the middle: + adds no space of its own, unlike the comma in print.

Two methods are on the syllabus. upper() returns a copy in capitals and lower() returns a copy in small letters. Both return a new string and leave the original untouched, so s.upper() on its own line accomplishes nothing — you must use the returned value or assign it.

city = "delhi"
print(city.upper())   # DELHI
print(city)           # delhi  (unchanged)
city = city.upper()
print(city)           # DELHI

Traversal visits each character. The direct form gives you the characters; the indexed form gives you positions as well.

s = "India"
for ch in s:
    print(ch, end=" ")
print()

for i in range(len(s)):
    print(i, s[i])

The operator in tests whether one string occurs inside another, which makes the vowel-counting program short. Converting each character with lower() means capital vowels are counted too.

s = input("Enter a string: ")
count = 0
for ch in s:
    if ch.lower() in "aeiou":
        count = count + 1
print("Number of vowels =", count)

Reversing a string can be done in one line with a slice, or with the loop the examiner may ask for. In the loop version each new character is placed in front of what has been built so far:

s = input("Enter a string: ")
rev = ""
for ch in s:
    rev = ch + rev
print("Reversed:", rev)

Trace it on "cat": rev becomes "c", then "ac", then "tac". Writing rev = rev + ch instead would simply rebuild the original string.

A palindrome is a word that reads the same forwards and backwards, such as level, nitin or malayalam. Converting to one case first makes the test fair for words typed with a capital letter.

s = input("Enter a word: ").lower()
if s == s[::-1]:
    print("Palindrome")
else:
    print("Not a palindrome")
Length and character len(s) , s[0] , s[-1] Spaces count as characters and occupy an index.
Slice s[2:5] Characters at index 2, 3 and 4 — the stop is excluded.
Reverse s[::-1] A step of -1 walks the string from the end to the start.
Join and repeat "ab" + "cd" , "ab" * 3 + needs two strings; * needs a string and an integer.
Case methods s.upper() , s.lower() They return a new string; the original is unchanged because strings are immutable.
Remember
  • A string is a sequence of characters in single or double quotes; indexing starts at 0 and -1 is the last character.
  • Slicing excludes the stop position; s[::-1] gives the whole string reversed.
  • Strings are immutable — s[0] = "R" raises a TypeError; build a new string instead.
  • + concatenates two strings (use str() on a number first); * repeats a string a whole number of times.
  • upper() and lower() return new strings and leave the original unchanged.
  • Traverse with for ch in s, or with for i in range(len(s)) when you need the index.

The Standard Programs and the Errors to Avoid

Quick answer What a full-mark program answer contains, the shape shared by every classic CBSE program, and the three mistakes that cost the most marks: off-by-one ranges, changing a list while looping over it, and = versus ==.

Programming questions are marked on more than the output. A full-mark answer generally contains four things: an input step with a clear prompt and the right conversion, a processing step using the correct loop or condition, an output step that prints a labelled result rather than a bare number, and correct indentation throughout. Sensible variable names such as total and largest make the logic obvious to whoever reads your paper.

Almost every program on this syllabus is one of three shapes. The accumulator shape sets a variable outside the loop and builds it up inside — sum of n numbers (start at 0) and factorial (start at 1). The running best shape sets the answer to the first candidate and improves it — largest of three, largest in a list. The build a new sequence shape starts with an empty string or list and adds to it — reversing a string, counting vowels. Recognise the shape and the code writes itself.

Error 1: the off-by-one range. Because the stop value of range() is excluded, a loop meant to run from 1 to n must be written range(1, n + 1). Writing range(1, n) silently drops the last value, so a table of 7 stops at 7 × 9 and a factorial of 5 comes out as 24. The mirror image happens with indices: range(len(marks)) gives 0 up to len - 1, which is exactly the set of valid indices, whereas range(1, len(marks)) skips item 0 and range(len(marks) + 1) runs one step too far and raises an IndexError. Before you hand in a loop, check the very first and the very last value it produces; those are the only two places this error hides.

Error 2: modifying a list while iterating over it. A for loop walks a list by position. If you delete items during the walk, the remaining items shift left while the position counter keeps moving right, so some items are stepped over entirely.

nums = [1, 2, 2, 3, 2, 4]
for n in nums:
    if n == 2:
        nums.remove(n)
print(nums)      # [1, 3, 2, 4]  -- one 2 survives

The loop looks correct and even runs without an error message, which is what makes it dangerous. The fix is to leave the list you are walking alone. Either iterate over a copy, using the full slice nums[:], or build a new list of the items you wish to keep:

nums = [1, 2, 2, 3, 2, 4]
for n in nums[:]:
    if n == 2:
        nums.remove(n)
print(nums)      # [1, 3, 4]

nums = [1, 2, 2, 3, 2, 4]
keep = []
for n in nums:
    if n != 2:
        keep.append(n)
print(keep)      # [1, 3, 4]

Error 3: confusing = with ==. The single = is the assignment operator: it stores a value in a variable. The double == is the equality operator: it compares two values and produces True or False. Writing if n = 5: is a SyntaxError in Python, and the program will not run at all — which is at least a loud failure. The quiet failure is the opposite slip inside a loop:

total == total + i    # compares, then throws the result away
total = total + i     # correct: stores the new total

The first line is legal Python, produces no error, and leaves total unchanged for ever, so the program prints a wrong answer with complete confidence. Read every line inside a loop and ask whether it is meant to store or to test.

Three smaller mistakes are worth a final look. Forgetting the colon after an if, while or for header gives a SyntaxError. Indenting inconsistently — four spaces on one line and three on the next — gives an IndentationError. And comparing raw input to a number never works: input() returns the string "10", and "10" == 10 is False, so the condition if input("Enter: ") == 10: can never be true. Convert first with int().

Finally, practise the dry run. Draw a small table with one column per variable, write the value after each pass of the loop, and stop when the condition fails. Two minutes of dry running catches off-by-one errors and wrong starting values far more reliably than reading the code again.

Off-by-one fix range(1, n + 1) Gives 1 to n inclusive; range(1, n) drops the last value.
Index range range(len(marks)) 0 to len - 1 — exactly the valid indices.
Safe deletion for x in nums[:] Iterate over a copy so removals do not shift the items you have yet to see.
Assign vs compare = stores , == tests if n = 5: is a SyntaxError; total == total + i is legal but does nothing.
Comparing input int(input("n: ")) == 10 Without int(), the comparison is "10" == 10, which is False.
Remember
  • A full-mark program shows prompted input with conversion, correct processing, a labelled output and correct indentation.
  • Off-by-one: use range(1, n + 1) for 1 to n, and range(len(x)) for valid indices — check the first and last value the loop produces.
  • Never remove items from a list you are iterating over; loop over a copy nums[:] or build a new list.
  • = assigns, == compares; if n = 5: is a SyntaxError, while total == total + i runs silently and gives a wrong answer.
  • Missing colons give SyntaxError; uneven indentation gives IndentationError.
  • input() returns a string, and "10" == 10 is False — convert with int() before comparing.

Quick reference

Every term, tag and rule from this chapter in one place — screenshot it before your exam.

name = value
Assignment
int, float, str, bool
Data types
n = int(input("Enter n: "))
Reading a number
17 / 5 = 3.4 , 17 // 5 = 3
Division pair
n % 2 == 0
Even test
if condition:
if header
== compares , = assigns
Compare vs assign
if ... elif ... else:
Multi-way choice
and , or , not
Logical operators
4 spaces = one level
Block rule
while condition:
while header
i = 1 ... i = i + 1
Counting up
total = total + value
Sum accumulator
fact = fact * i
Factorial accumulator
entry-controlled
Loop type
for var in range(...):
for header
range(5)
One argument
range(2, 6)
Two arguments
range(5, 0, -1)
Three arguments
range(1, n + 1)
1 to n inclusive
marks = [78, 85, 62] ; len(marks)
Create and measure
marks[-1]
Last item
marks[1:4]
Slice
append(x) , insert(p, x) , remove(v) , pop(i)
Add and remove
marks.sort() , marks.reverse()
Reorder
len(s) , s[0] , s[-1]
Length and character
s[2:5]
Slice
s[::-1]
Reverse
"ab" + "cd" , "ab" * 3
Join and repeat
s.upper() , s.lower()
Case methods
range(1, n + 1)
Off-by-one fix
range(len(marks))
Index range
for x in nums[:]
Safe deletion
= stores , == tests
Assign vs compare
int(input("n: ")) == 10
Comparing input

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 for loop and range() easy

How many times does the loop <code>for i in range(1, 6):</code> repeat?

Q2 Variables and input easy

What is the data type of the value returned by <code>input()</code>?

Q3 Lists easy

Given <code>marks = [10, 20, 30, 40]</code>, what does <code>print(marks[-2])</code> display?

Q4 Operators easy

What is the output of <code>print(17 // 5)</code>?

Q5 Strings medium

Given <code>s = "Computer"</code>, what does <code>print(s[2:5])</code> display?

Q6 Strings medium

What is printed by <code>city = "delhi"</code> followed by <code>city.upper()</code> and then <code>print(city)</code>?

Q7 break and continue medium

What is the output of: <code>for i in range(1, 6):</code> / <code>if i == 3: continue</code> / <code>print(i, end=" ")</code>?

Q8 List methods medium

After <code>fees = [100, 200, 300]</code> and <code>x = fees.pop(0)</code>, what are x and fees?

Q9 Common errors medium

What happens when Python runs the line <code>if marks = 40:</code>?

Q10 List methods hard

What does <code>print(marks)</code> show after <code>marks = [3, 1, 2]</code> and <code>marks = marks.sort()</code>?

Q11 Nested loops hard

How many stars does this print? <code>for i in range(3):</code> / <code>for j in range(4):</code> / <code>print("*", end="")</code>

Q12 Common errors hard

What is printed by: <code>nums = [1, 2, 2, 3, 2, 4]</code> / <code>for n in nums: if n == 2: nums.remove(n)</code> / <code>print(nums)</code>?

NCERT solutions & previous-year questions

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

NCERT questions 8

1 What is a variable? State the rules for naming a variable (identifier) in Python.Variables and data types

A variable is a named location in memory used to store a value. In Python a variable is created the moment a value is assigned to it with the assignment operator =; there is no separate declaration statement, and the data type is decided by the value assigned.

The rules for a valid identifier are:

  • It may contain only letters (A–Z, a–z), digits (0–9) and the underscore _.
  • It must not begin with a digit.
  • It must not contain a space or a special symbol such as @, -, # or $.
  • It must not be a keyword (a reserved word such as if, else, for, while, break, True).
  • Identifiers are case sensitive, so marks and Marks are different variables.

Valid: total_fee, marks1, _temp. Invalid: total fee (space), 2ndterm (starts with a digit), class (keyword).

2 Why is indentation important in Python? What error occurs if it is wrong?Indentation

Indentation is the blank space left at the start of a line. In most languages a block of statements is marked by braces and indentation is only a habit that helps the reader. Python has no braces, so indentation is part of the syntax: the indented lines below a header such as if, while or for are exactly the statements that the header controls.

The rules are that the header line ends with a colon, every statement in one block is indented by the same amount, and a nested block is indented one level further. The usual convention is four spaces per level. Tabs and spaces should not be mixed, because editors differ in the width they draw a tab.

If the indentation is missing or uneven, Python stops with an IndentationError and the program does not run. Indentation can also change the meaning of correct-looking code — a print indented inside a loop runs on every pass, while the same print written at the outer level runs only once after the loop.

3 Differentiate between the while loop and the for loop, with one example of each.Loops

Both repeat a block of statements, but they suit different situations.

  • A for loop repeats once for each item of a sequence (a range, list or string). It is used when the number of repetitions is known or countable.
  • A while loop repeats as long as a condition is true. It is used when the number of repetitions is not known in advance.
  • In a for loop the loop variable is advanced automatically; in a while loop you must initialise and update the control variable yourself, and forgetting the update causes an infinite loop.
# for: a known count of 5 repetitions
for i in range(1, 6):
    print(i, end=" ")

# while: repetitions decided by the user
value = int(input("Enter a number (0 to stop): "))
while value != 0:
    print("You entered", value)
    value = int(input("Enter a number (0 to stop): "))

Both are entry-controlled: the condition, or the availability of a next item, is checked before each pass, so either loop may run zero times.

4 Explain the range() function with all three of its forms, giving the values produced by each.range()

range() is a built-in function that generates a sequence of integers for a for loop. In every form the start value is included and the stop value is excluded.

  • range(stop) — counts from 0. range(5) gives 0, 1, 2, 3, 4.
  • range(start, stop) — counts from start. range(2, 6) gives 2, 3, 4, 5.
  • range(start, stop, step) — adds step each time. range(1, 10, 2) gives 1, 3, 5, 7, 9.

The step may be negative, in which case the values count downwards: range(5, 0, -1) gives 5, 4, 3, 2, 1 (0 is excluded). If the start has already passed the stop in the direction of travel, the range is empty and the loop body never runs — range(5, 1) produces no values, because the default step of +1 cannot reach downwards.

The number of values in range(a, b) is b - a. To count from 1 to n inclusive, write range(1, n + 1).

5 Differentiate between break and continue with a suitable example.break and continue

break terminates the loop immediately. Control passes to the first statement after the loop and no further items are processed.

continue skips only the remaining statements of the current pass. The loop then continues with the next item as usual.

for i in range(1, 8):
    if i == 4:
        break
    print(i, end=" ")
# Output: 1 2 3

for i in range(1, 8):
    if i == 4:
        continue
    print(i, end=" ")
# Output: 1 2 3 5 6 7

Note also that in a nested loop, a break written inside the inner loop ends only the inner loop; the outer loop carries on with its next value.

6 Explain any five list methods with an example of each.List methods

Taking fees = [1200, 1500, 900] as the starting list:

  • append(item) — adds one item at the end. fees.append(2000) gives [1200, 1500, 900, 2000].
  • insert(pos, item) — inserts at the given position, shifting later items right. fees.insert(1, 1000) gives [1200, 1000, 1500, 900, 2000].
  • remove(value) — deletes the first occurrence of that value; raises a ValueError if it is absent. fees.remove(900) gives [1200, 1000, 1500, 2000].
  • pop(index) — removes the item at that position and returns it; with no argument it removes the last item. x = fees.pop(0) sets x to 1200 and leaves [1000, 1500, 2000].
  • sort() — arranges the list in ascending order in place; sort(reverse=True) gives descending order.

A sixth method, reverse(), reverses the order of the items in place. Remember that remove() takes a value while pop() takes a position, and that sort() and reverse() return None — so fees = fees.sort() destroys the list.

7 Write a program to input a string and count the number of vowels in it.String traversal
s = input("Enter a string: ")
count = 0

for ch in s:
    if ch.lower() in "aeiou":
        count = count + 1

print("Number of vowels =", count)

How it works: the counter is set to 0 before the loop. The for loop traverses the string one character at a time. ch.lower() converts the character to small letters so that capital vowels are counted as well, and the in operator checks whether it appears in the string "aeiou". For the input "Education" the output is 5.

8 Write a program to find the factorial of a number entered by the user, using a loop.Loops and accumulators
n = int(input("Enter a number: "))
fact = 1

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

print("Factorial of", n, "is", fact)

Points that earn the marks: fact is initialised to 1, not 0, because a product accumulator starting at 0 would give 0 every time. The range is range(1, n + 1) so that n itself is included — range(1, n) would stop one short. For n = 0 the loop body never runs and the program correctly prints 1.

The same result with a while loop:

n = int(input("Enter a number: "))
fact = 1
i = 1
while i <= n:
    fact = fact * i
    i = i + 1
print("Factorial of", n, "is", fact)

Previous-year board questions 6

Q1 Write the output of the following code: <code>for i in range(5, 0, -1): print(i, end=" ")</code> 1 mark

Output: 5 4 3 2 1

The step of −1 counts downwards from the start value 5, and the stop value 0 is excluded, so the loop ends after printing 1. end=" " keeps all the values on one line.

Q2 Predict the output of the following code:<br><code>nums = [4, 8, 15, 16, 23, 42]</code> / <code>print(nums[1:4])</code> / <code>print(nums[-1])</code> / <code>print(len(nums))</code> / <code>nums.append(50)</code> / <code>nums.remove(15)</code> / <code>print(nums)</code> 2 marks
[8, 15, 16]
42
6
[4, 8, 16, 23, 42, 50]

Explanation:

  • nums[1:4] takes the items at indices 1, 2 and 3; index 4 is excluded.
  • nums[-1] is the last item, 42.
  • len(nums) is 6 at that point, before anything is added or removed.
  • append(50) adds 50 at the end and remove(15) deletes the value 15, leaving the final list shown.
Q3 Find the errors in the following code, underline them and rewrite the corrected code:<br><code>n = int(input("Enter a number"))</code> / <code>if n % 2 = 0</code> / <code>print("Even")</code> / <code>else:</code> / <code>print("Odd")</code> 3 marks

Errors:

  1. = has been used for comparison in the condition; the equality operator is ==.
  2. The if header has no colon at the end.
  3. The bodies of the if and the else are not indented, so Python cannot tell which statements each branch controls.

Corrected code:

n = int(input("Enter a number: "))
if n % 2 == 0:
    print("Even")
else:
    print("Odd")
Q4 Write a program to input three numbers and display the largest of them. 3 marks
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
c = int(input("Enter third number: "))

if a >= b and a >= c:
    print("Largest =", a)
elif b >= a and b >= c:
    print("Largest =", b)
else:
    print("Largest =", c)

Note: >= is used rather than > so that equal values are handled correctly — with a strict >, two equal largest values can fail every test. Each input is wrapped in int(), because input() returns a string and strings would be compared alphabetically, giving a wrong answer for values such as 9 and 10.

Q5 Write a program to input a word and check whether it is a palindrome. 3 marks

A palindrome reads the same forwards and backwards, for example level, nitin or malayalam.

word = input("Enter a word: ").lower()

if word == word[::-1]:
    print(word, "is a palindrome")
else:
    print(word, "is not a palindrome")

word[::-1] slices the whole string with a step of −1, producing it in reverse. Calling .lower() on the input makes the test fair for a word typed with a capital letter.

If the question asks for a loop instead of a slice, build the reversed string first:

word = input("Enter a word: ").lower()
rev = ""
for ch in word:
    rev = ch + rev

if word == rev:
    print("Palindrome")
else:
    print("Not a palindrome")
Q6 Write a program that accepts n numbers from the user into a list and then displays the list in reverse order, the sum of its elements and the largest element. 5 marks
n = int(input("How many numbers? "))
nums = []

for i in range(n):
    value = int(input("Enter number " + str(i + 1) + ": "))
    nums.append(value)

total = 0
largest = nums[0]

for value in nums:
    total = total + value
    if value > largest:
        largest = value

nums.reverse()

print("List in reverse order:", nums)
print("Sum =", total)
print("Largest =", largest)

Points that earn the marks:

  • The list is created empty and filled with append() inside a for loop that runs n times — range(n) gives 0 to n−1, which is n values.
  • Each input is converted with int(); str(i + 1) is needed inside the prompt because + can only join a string to a string.
  • total starts at 0 and largest starts at nums[0], not at 0, so negative values are handled correctly.
  • reverse() reverses the list in place and returns None, so it is called on its own line and never assigned.

Part of Priodemy for School

Interactive Maths & Science — free with every school on Priodemy EduSuite. Explore more chapters and labs on the Priodemy for School hub.

Ask AI