Class 9Computer ScienceFull chapter

Getting Started with Python

Python is the language CBSE chose for Class 9 because it reads almost like English. Learn to write and dry-run short programs, use input() correctly, apply operator precedence and name the error the examiner shows you.

Why Python, and the Two Ways to Run It

Quick answer What a programming language is, the features that made Python the school-level choice, and the difference between interactive mode and script mode.

A program is a set of instructions written for a computer to carry out a task. A programming language is the set of words and rules used to write those instructions. Python is a high-level language, which means it is written in words close to English rather than in the 0s and 1s the machine actually understands.

The computer cannot run English. A translator program converts your code into machine language. Python uses an interpreter — a translator that takes your program one statement at a time, converts it and runs it immediately. A compiler, used by languages such as C++, translates the whole program at once before running any of it. Python reports an error together with the line number where it was found, which is very useful while learning. A grammar mistake is reported before the program starts running; other errors stop the program at the line where they occur.

You should be able to list the features of Python. Learn these five:

  • Simple and easy to read. The syntax uses ordinary words like if, else, while and print.
  • Free and open source. It can be downloaded and used without paying, and its source code may be studied and modified.
  • Interpreted. Statements are translated and executed one by one.
  • Portable (platform independent). The same .py file runs on Windows, Linux or macOS, provided Python is installed.
  • Rich library support. Ready-made modules exist for mathematics, graphics, files and much more, so you do not have to write everything yourself.

One more feature is worth stating because it is tested: Python is case sensitive. Marks, marks and MARKS are three different names, and Print is not the same as print.

Where you type your code. Most schools use IDLE, the editor that is installed along with Python itself. IDLE stands for Integrated Development and Learning Environment. Other editors exist, and different labs set up different ones, so describe what your school uses rather than assuming everyone has the same screen.

Interactive mode. When you open IDLE you see the Python shell with the prompt >>>. Type one statement, press Enter, and the result appears at once.

>>> 12 + 8
20
>>> print("Namaste")
Namaste

Notice that in interactive mode, typing 12 + 8 alone displays the answer. That happens only at the >>> prompt. Interactive mode is useful for testing one line, checking an expression or trying an operator — but nothing you type is saved.

Script mode. Here you open a new file, type the complete program, save it with a .py extension, and then run the whole file. The output appears in the shell window. Script mode is what you use for any real program and for practical examinations, because the program is stored and can be corrected and run again.

# area.py — a program in script mode
length = 12
breadth = 5
print("Area =", length * breadth)

What the examiner expects. In a "differentiate" question, give two clean contrasts: interactive mode executes one statement at a time and does not store the program, while script mode executes a saved .py file as a whole and the program can be reused. Do not merely say "one is fast and one is slow".

Source file extension .py file · Every Python program file is saved with this extension.
Interactive prompt >>> shell · Three greater-than signs shown by the Python shell.
Translator used Interpreter (line by line) — · Compiler translates the entire program at once instead.
Case sensitivity print ≠ Print — · A capital letter creates a completely different name.
Remember
  • Python is a high-level, interpreted, free, portable and case-sensitive language.
  • An interpreter translates and runs one statement at a time; a compiler translates the whole program first.
  • Interactive mode uses the >>> prompt, shows results immediately and saves nothing.
  • Script mode runs a saved .py file as a whole and is used for practicals.
  • IDLE stands for Integrated Development and Learning Environment.
  • In interactive mode an expression alone shows its value; in a script you must use print().

Variables, Data Types and input()

Quick answer Naming rules that examiners test, the four data types in the syllabus, and the fact that input() always hands you a string.

A variable is a named location in memory used to store a value that can change while the program runs. You create a variable simply by assigning a value to it with the assignment operator =. The name goes on the left, the value on the right.

marks = 78
name = "Ananya"
price = 249.50

Read marks = 78 as "store 78 in marks", not as "marks equals 78". Python does not need you to declare the type in advance; it decides the type from the value you store. Storing a new value replaces the old one.

Rules for naming variables. A variable name is also called an identifier. The rules are frequently asked:

  • It may contain letters (A–Z, a–z), digits (0–9) and the underscore _.
  • It must not begin with a digit. marks1 is valid; 1marks is not.
  • It must not contain a space or any special character such as @, # or -. Use total_marks, not total marks.
  • It must not be a keyword — a word reserved by Python for its own use, such as if, else, while, for, True, None or import.
  • Names are case sensitive, so Total and total are two separate variables.

A good name also describes what it holds. si for simple interest is acceptable in an exam; x1 for a student's name is not helpful.

Data types. A data type tells Python what kind of value a variable holds and what may be done with it. Four are in the Class 9 syllabus.

  • int — whole numbers, positive or negative, with no decimal point: 78, -15, 0.
  • float — numbers with a decimal point: 249.50, -3.5, 98.6.
  • str — a string, that is, a sequence of characters inside quotes: "Ananya", "9-A", "2026". Note that "2026" in quotes is a string, not a number.
  • bool — Boolean, holding only True or False, always with a capital first letter.

The built-in function type() reports the data type, which is handy in interactive mode.

>>> type(78)
<class 'int'>
>>> type(9 > 4)
<class 'bool'>

input() and the mistake almost everyone makes. The input() function reads what the user types from the keyboard. The text inside its brackets is the message shown to the user, called the prompt. The crucial rule: input() always returns a string, even when the user types digits.

a = input("Enter first number: ")
b = input("Enter second number: ")
print(a + b)

If the user types 12 and 8, this prints 128, not 20 — because + between two strings joins them end to end. This joining is called concatenation.

To do arithmetic you must convert, using int() for whole numbers or float() for decimals. This conversion is called type casting.

a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print("Sum =", a + b)

Now 12 and 8 give Sum = 20. Use float() when the value can have a decimal part, such as a price in rupees or a percentage. Note the two closing brackets — one for input and one for int. Forgetting one is a common syntax error.

What the examiner expects. Whenever a question says "accept from the user", write int(input(...)) or float(input(...)). A program that reads marks with a bare input() and then tries to add them joins the digits as text instead of adding them, and the answer is wrong.

Read a whole number n = int(input("Enter n: ")) int · Two closing brackets — one for input, one for int.
Read a decimal number p = float(input("Price: ")) float · Use for money, marks percentages, measurements.
Check a data type type(value) class · Displays &lt;class 'int'&gt;, &lt;class 'str'&gt; and so on.
Invalid identifier examples 1marks, total marks, if — · Starts with a digit, contains a space, is a keyword.
String joining "12" + "8" → "128" str · + concatenates strings; it does not add them.
Remember
  • A variable is a named memory location whose value can change; = assigns a value to it.
  • Identifiers may use letters, digits and underscore, must not start with a digit and must not be keywords.
  • The four syllabus data types are int, float, str and bool; type() reports which one a value is.
  • True and False are the only bool values and are written with a capital letter.
  • input() always returns a string, so 12 + 8 typed by the user gives 128 without conversion.
  • Wrap input() in int() or float() — type casting — before doing arithmetic.

Operators and Operator Precedence

Quick answer Arithmetic, relational and logical operators, what each returns, and the order Python uses when several appear in one expression.

An operator is a symbol that performs an operation on values. The values it works on are called operands. In 15 + 4, the + is the operator and 15 and 4 are the operands.

Arithmetic operators perform calculations. Seven are used at this level.

  • + addition — 15 + 4 gives 19
  • - subtraction — 15 - 4 gives 11
  • * multiplication — 15 * 4 gives 60
  • / division — 15 / 4 gives 3.75
  • // floor division, the quotient with the decimal part discarded — 15 // 4 gives 3
  • % modulus, the remainder — 15 % 4 gives 3
  • ** exponent, or power — 15 ** 2 gives 225

Two points here are commonly tested. First, in Python 3 the ordinary division operator / always produces a float: 10 / 2 gives 5.0, not 5. Write the .0 in your answer. Second, % gives the remainder, which is the standard way to test divisibility — a number n is even when n % 2 == 0, and divisible by 5 when n % 5 == 0.

Relational (comparison) operators compare two values and always give a bool result, True or False. There are six: == equal to, != not equal to, > greater than, < less than, >= greater than or equal to, and <= less than or equal to.

>>> 45 > 33
True
>>> 45 == 45.0
True
>>> "abc" != "ABC"
True

The double equal sign == asks a question; the single = stores a value. Mixing them up is dealt with in the errors section, but fix the idea now: marks = 90 puts 90 into marks, while marks == 90 checks whether marks is 90.

Logical operators combine conditions. There are three, written as words.

  • and — True only when both conditions are True.
  • or — True when at least one condition is True.
  • not — reverses the result: not True is False.
marks = 82
attendance = 90
print(marks >= 75 and attendance >= 75)

Both conditions are True, so this prints True. Had attendance been 60, and would give False while or would still give True.

Operator precedence is the order in which Python evaluates operators when several occur in one expression. From highest to lowest:

  1. Parentheses ( )
  2. Exponent **
  3. Unary minus, as in -5
  4. *, /, //, % — evaluated left to right
  5. +, - — evaluated left to right
  6. Relational operators < <= > >= == !=
  7. not, then and, then or

Work an example the way the examiner wants it — one step per line.

10 + 20 * 2 // 5 - 3
= 10 + 40 // 5 - 3        # * first
= 10 + 8 - 3              # // next
= 18 - 3                  # + and - left to right
= 15

Parentheses override everything, so (10 + 20) * 2 gives 60 while 10 + 20 * 2 gives 50. One special case: ** groups from the right, so 2 ** 3 ** 2 is 2 ** 9, which is 512, not 64.

What the examiner expects. In "evaluate the expression" questions, show the intermediate steps. The working makes your method visible and a slip in one step is far easier to find than in a single bare answer.

Floor division vs division 15 // 4 = 3 , 15 / 4 = 3.75 int / float · // discards the decimal part; / always returns a float.
Remainder test n % 2 == 0 → even bool · n % 2 == 1 means odd for positive integers.
Power 5 ** 3 = 125 number · Right associative: 2 ** 3 ** 2 = 512.
Precedence order ( ) → ** → * / // % → + - → comparisons → not → and → or rule · Parentheses always win; show each step in the answer.
Assignment vs comparison = stores , == compares — · if x = 5: is a syntax error; if x == 5: is correct.
Remember
  • / always gives a float in Python 3: 10 / 2 is 5.0, while 10 // 2 is 5.
  • % gives the remainder and is used to test even, odd or divisibility.
  • Relational operators always return a bool value, True or False.
  • Logical operators are the words and, or and not — never the symbols && or ||.
  • Precedence order: ( ) then ** then * / // % then + - then relational then not, and, or.
  • ** groups right to left, so 2 ** 3 ** 2 equals 512.

Decision Making: if, elif and else

Quick answer How Python chooses between paths, why the colon and the indentation are part of the grammar, and the standard exam programs.

Up to now every statement ran in order, top to bottom. That is called sequence. A conditional statement lets the program choose: run these lines only if a condition is True. This is called selection, and in Python it is written with if, elif and else.

The simple form has a condition, a colon, and an indented block:

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

Two pieces of punctuation are compulsory. The colon : ends the if line. The lines that belong to the if are then pushed in from the left margin — that is indentation, and in Python it is not decoration, it is syntax. The indented lines form a block or suite. Most textbooks and IDLE use four spaces; whatever you choose, keep it identical for every line of the same block. If you mix spaces and tabs, or line the statements up unevenly, Python reports an IndentationError.

if…else supplies the alternative path. Exactly one of the two blocks runs.

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

Note that else is written at the same level as if, has a colon, and never carries a condition of its own.

if…elif…else handles more than two possibilities. elif is short for "else if". Python tests the conditions from the top; the moment one is True it runs that block and skips all the rest.

# Grade calculator
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")

The order matters. If you tested marks >= 33 first, then 95 would also satisfy it and print Grade D, and the later branches would never be reached. Arrange the conditions from the strictest to the loosest.

You may write as many elif branches as you need, but at most one else, and it must come last. The else is optional — leave it out and, if nothing matches, nothing is printed.

Two more standard programs. Even or odd, using the remainder:

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

Largest of three numbers, using a logical operator:

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)

Trace it once with 45, 90 and 60. The first condition is False because 45 is not at least 90. The second is True, so it prints Largest = 90 and stops.

Nested if. An if placed inside another if block is a nested if; the inner block is indented one level further. It is useful when a second check only makes sense after the first has passed, for example checking a discount only after confirming the bill is above a limit. Keep the levels obvious, because deeply nested code is where indentation mistakes appear.

What the examiner expects. When you write a conditional program in the answer sheet, indent visibly — leave a clear gap of about four spaces — and put the colon at the end of every if, elif and else line. Missing colons and flat, unindented code count as errors even when the logic is right.

Basic form if condition: → indented block statement · Colon compulsory; block indented, usually four spaces.
Multi-way form if … elif … elif … else statement · Many elif allowed, at most one else and it comes last.
Standard indentation 4 spaces spaces · Be consistent; never mix tabs and spaces in one block.
Even / odd test if n % 2 == 0: bool · True means even; the else branch handles odd.
Remember
  • Every if, elif and else line ends with a colon; the statements under it are indented.
  • Indentation is syntax in Python — uneven or mixed indentation gives an IndentationError.
  • elif means else-if; Python runs the first block whose condition is True and skips the rest.
  • There can be many elif branches but at most one else, and it must be last and condition-free.
  • Order conditions strictest first, or a loose condition will capture every case.
  • Use n % 2 == 0 to test even, and and / or to combine two comparisons.

Repetition: while Loops and for with range()

Quick answer The two loops in the syllabus, the three parts every while loop must have, and how range() decides which numbers a for loop visits.

A loop repeats a block of statements. Repetition is also called iteration. Without a loop, printing a multiplication table would need ten almost identical print() lines; with a loop it needs two.

The while loop repeats as long as a condition stays True. It is the right choice when you do not know in advance how many repetitions are needed.

i = 1
total = 0
while i <= 10:
    total = total + i
    i = i + 1
print("Sum of first 10 natural numbers =", total)

This prints Sum of first 10 natural numbers = 55. Every correct while loop has three parts, and you should be able to point them out:

  1. Initialisationi = 1, before the loop, sets the starting value.
  2. Conditioni <= 10, tested before each repetition. When it becomes False the loop ends.
  3. Updatei = i + 1, inside the loop, moves the variable towards the condition becoming False.

Leave out the update and the condition never becomes False. The loop then runs for ever; this is an infinite loop. It is a logical error, not a syntax error, so Python reports nothing — the program simply never stops. In IDLE and in most terminals you interrupt it with Ctrl+C; some other editors give you a stop button instead. Being able to explain an infinite loop and give i = i + 1 as the missing statement is a common short answer.

Notice also that i = i + 1 is not algebra. It means "take the current value of i, add 1, and store the result back in i". The short form i += 1 does the same thing.

The for loop repeats a fixed number of times. It is normally used with the built-in range() function, which generates a sequence of whole numbers.

  • range(stop) — starts at 0 and stops before stop. range(5) gives 0, 1, 2, 3, 4.
  • range(start, stop)range(1, 6) gives 1, 2, 3, 4, 5.
  • range(start, stop, step)range(2, 11, 2) gives 2, 4, 6, 8, 10.

The single rule to memorise: the stop value is never included. To count 1 to 10 you must write range(1, 11). A negative step counts downwards, so range(5, 0, -1) gives 5, 4, 3, 2, 1.

The multiplication table is the classic for program:

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

For n = 7 the first line printed is 7 x 1 = 7 and the last is 7 x 10 = 70. The loop variable i takes each value from the range in turn; you do not initialise or update it yourself, which is the main convenience of a for loop over a while loop.

Factorial is another program worth knowing by heart:

n = int(input("Enter a number: "))
f = 1
for i in range(1, n + 1):
    f = f * i
print("Factorial of", n, "is", f)

Start f at 1, not 0 — multiplying by 0 would make every answer 0. That single line is worth checking in every product-based program you write.

A for loop can also step through the characters of a string:

for ch in "INDIA":
    print(ch)

This prints I, N, D, I and A on five separate lines.

What the examiner expects. Choose for when the number of repetitions is known (print a table, sum ten numbers) and while when it depends on a condition (keep asking until the user types 0). For a "how many times does this loop run" question, write out the values of the loop variable in a small trace table rather than guessing.

while structure initialise → test condition → update rule · Missing the update creates an infinite loop.
range with one argument range(5) → 0 1 2 3 4 sequence · Starts at 0, stop value excluded.
range with three arguments range(2, 11, 2) → 2 4 6 8 10 sequence · Third value is the step; it may be negative.
Count 1 to n for i in range(1, n + 1): loop · The + 1 is needed because stop is excluded.
Increment shortcut i += 1 is same as i = i + 1 — · Reads the old value, adds 1, stores it back.
Remember
  • A while loop needs initialisation, a condition and an update; a missing update gives an infinite loop.
  • An infinite loop is a logical error — Python reports no message, the program just never ends.
  • range(stop) starts at 0; range(start, stop) starts at start; the stop value is always excluded.
  • To count 1 to 10 write range(1, 11); a negative step such as range(5, 0, -1) counts down.
  • A for loop manages its own loop variable, so use it when the count is known in advance.
  • In a factorial or product program, start the accumulator at 1, not 0.

Common Errors and Exam-Style Programs

Quick answer The four errors Class 9 students meet most, how to name each one in an answer, and a set of complete programs of the kind CBSE sets.

Errors are called bugs, and removing them is debugging. Examiners often print a short program with a mistake and ask you to name the error or rewrite the code correctly, so learn the exact error names. Learn the name — IndentationError, NameError, TypeError, ValueError, SyntaxError — rather than the sentence printed after it, because the wording of that message is chosen by the interpreter and changes a little from one Python version to another.

There are three broad categories. A syntax error breaks a grammar rule of the language and the program does not run at all. A run-time error appears while the program is running, when it meets something it cannot do. A logical error lets the program run and finish, but the answer is wrong — the hardest kind, because Python prints no message. Now the four specific errors in the syllabus.

1. IndentationError. Raised when the indentation is missing or uneven.

marks = 80
if marks >= 33:
print("Pass")          # IndentationError: expected an indented block

The print belongs to the if, so it must be pushed in by four spaces. The same error appears when two statements in one block start at different columns, or when tabs and spaces are mixed. Fix: indent every line of the block by the same amount.

2. NameError. Raised when you use a name that has not been given a value yet — usually a spelling or capitalisation slip, since Python is case sensitive.

Marks = 80
print(marks)           # NameError: name 'marks' is not defined

Fix: use the same spelling and the same capital letters everywhere. Forgetting the quotes around a piece of text causes the same error, because print(Pass) makes Python look for a variable called Pass.

3. TypeError from adding a string and a number. Raised when an operator is used on types it cannot combine.

age = "15"
print(age + 1)         # TypeError: can only concatenate str (not "int") to str

Python will not guess whether you meant addition or joining. This is exactly what happens after input(), since input always returns a string. Fix: convert first with int(age) + 1, or, if you wanted text, convert the other way with age + str(1).

4. Using = instead of ==. The single = stores a value and cannot be used as a condition.

if marks = 90:         # SyntaxError: invalid syntax
    print("Excellent")

Fix: write if marks == 90:. Say clearly in your answer that = is the assignment operator and == is the relational operator that compares.

Two others worth recognising: a ValueError when int("hello") is attempted, and a plain SyntaxError when a colon or a closing bracket is missing.

Program 1 — simple interest.

# Simple interest calculator
p = float(input("Enter principal in rupees: "))
r = float(input("Enter rate of interest: "))
t = float(input("Enter time in years: "))
si = (p * r * t) / 100
print("Simple interest = Rs", si)

Program 2 — average of three subject marks.

m1 = int(input("Enter marks in subject 1: "))
m2 = int(input("Enter marks in subject 2: "))
m3 = int(input("Enter marks in subject 3: "))
total = m1 + m2 + m3
print("Total =", total)
print("Average =", total / 3)

Program 3 — sum of even numbers from 1 to 20.

total = 0
for i in range(2, 21, 2):
    total = total + i
print("Sum of even numbers up to 20 =", total)

The total displayed is 110.

Program 4 — count down using a while loop.

n = int(input("Enter starting number: "))
while n > 0:
    print(n, end=" ")
    n = n - 1
print("Liftoff")

What the examiner expects. In "find the error" questions, do three things: name the error, point to the exact line, and rewrite that line correctly. Naming the error on its own is only part of the answer.

IndentationError block not indented / uneven syntax · Indent every line of the block by the same four spaces.
NameError variable used before assignment run-time · Check spelling and capitals; Python is case sensitive.
TypeError "15" + 1 run-time · Fix with int("15") + 1 or "15" + str(1).
SyntaxError if x = 5: syntax · Use == in a condition; = only assigns.
ValueError int("hello") run-time · The text cannot be converted into a whole number.
Remember
  • Syntax errors stop the program from running; logical errors let it run but give a wrong answer.
  • IndentationError means a block is missing its indent or the lines are unevenly aligned.
  • NameError means the name was never assigned — usually a spelling or capital-letter slip.
  • Adding a str and an int raises a TypeError; convert with int() or str() first.
  • if marks = 90: is a SyntaxError because = assigns and == compares.
  • In error questions, name the error, quote the line and write the corrected line.

Quick reference

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

.py
Source file extensionfile
>>>
Interactive promptshell
Interpreter (line by line)
Translator used
print ≠ Print
Case sensitivity
print(item1, item2)
Display outputstatement
#
Comment symbolsymbol
sep = ' ' (one space)
Default separator
end = newline
Default line ending
n = int(input("Enter n: "))
Read a whole numberint
p = float(input("Price: "))
Read a decimal numberfloat
type(value)
Check a data typeclass
1marks, total marks, if
Invalid identifier examples
"12" + "8" → "128"
String joiningstr
15 // 4 = 3 , 15 / 4 = 3.75
Floor division vs divisionint / float
n % 2 == 0 → even
Remainder testbool
5 ** 3 = 125
Powernumber
( ) → ** → * / // % → + - → comparisons → not → and → or
Precedence orderrule
= stores , == compares
Assignment vs comparison
if condition: → indented block
Basic formstatement
if … elif … elif … else
Multi-way formstatement
4 spaces
Standard indentationspaces
if n % 2 == 0:
Even / odd testbool
initialise → test condition → update
while structurerule
range(5) → 0 1 2 3 4
range with one argumentsequence
range(2, 11, 2) → 2 4 6 8 10
range with three argumentssequence
for i in range(1, n + 1):
Count 1 to nloop
i += 1 is same as i = i + 1
Increment shortcut
block not indented / uneven
IndentationErrorsyntax
variable used before assignment
NameErrorrun-time
"15" + 1
TypeErrorrun-time
if x = 5:
SyntaxErrorsyntax
int("hello")
ValueErrorrun-time

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 Arithmetic operators easy

What is the output of print(10 / 2) in Python 3?

Q2 input() and type casting easy

What data type does the input() function always return?

Q3 Variable naming rules easy

Which of the following is NOT a valid variable name in Python?

Q4 Strings and operators medium

What is the output of print("5" + "5")?

Q5 Indentation medium

A student writes: if marks >= 33: followed on the next line by print("Pass") starting at the left margin. Which error appears?

Q6 Operator precedence medium

Evaluate: 2 + 3 * 4 ** 2

Q7 for loop and range() medium

Which values does for i in range(1, 10, 2) give to i?

Q8 Common errors medium

The statement print("10" + 5) produces which error?

Q9 Data types easy

What is the data type of the value produced by the expression 5 > 3?

Q10 while loop hard

A program sets x = 5. It then runs a while loop with the condition x > 0, and the body of the loop first prints x using end=" " and then does x = x - 2. What does the program print?

Q11 Modulus and floor division hard

If a = 17 and b = 5, what does print(a % b, a // b) display?

Q12 = versus == medium

Why does the line if marks = 90: fail in Python?

NCERT solutions & previous-year questions

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

NCERT questions 8

1 Differentiate between interactive mode and script mode in Python.Modes of working

Interactive mode works at the Python shell prompt >>>. You type one statement, press Enter, and the result is shown immediately. The statements are not stored, so the work is lost when the shell is closed. An expression typed on its own, such as 12 + 8, displays its value without needing print(). It is best for testing a single line or checking how an operator behaves.

Script mode is used to type a complete program in an editor window, save it with the .py extension and then run the whole file at once. The program is stored permanently and can be edited, corrected and run again. In script mode, output appears only where print() is used.

In short: interactive mode is one statement at a time and temporary; script mode is a full saved program run as a unit, and it is what practical work uses.

2 What is a variable? State the rules for naming a variable in Python.Variables and identifiers

A variable is a named location in memory that stores a value which may change during the execution of a program. A variable is created by assigning a value to it with the assignment operator =, for example marks = 78.

Rules for naming (identifiers):

  1. A name may contain letters, digits and the underscore _.
  2. It must not begin with a digit — marks1 is valid, 1marks is not.
  3. It must not contain spaces or special characters such as @, # or -.
  4. It must not be a Python keyword such as if, else, while, for or True.
  5. Names are case sensitive, so Total and total are different variables.

A meaningful name such as total_marks is preferred, because it makes the program easier to read.

3 Why must the value returned by input() be converted before it is used in a calculation? Explain with an example.input() and type casting

The input() function always returns a string, whatever the user types. When + is applied to two strings it joins them instead of adding them, so the program gives a wrong result rather than an error.

a = input("Enter first number: ")
b = input("Enter second number: ")
print(a + b)

If the user types 12 and 8, the output is 128, because "12" and "8" are joined end to end. This joining is called concatenation.

The correction is to convert the string into a number, which is called type casting. Use int() for whole numbers and float() for decimal values.

a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print("Sum =", a + b)

Now the output for the same input is Sum = 20.

4 Name the four basic data types used in Class 9 Python and give one example of each.Data types

A data type specifies the kind of value a variable holds and the operations that may be performed on it.

  • int — whole numbers with no decimal point, positive or negative. Example: age = 15.
  • float — numbers with a decimal point. Example: price = 249.50.
  • str — a string, a sequence of characters written inside single or double quotes. Example: name = "Ananya". Note that "2026" in quotes is a string, not a number.
  • bool — Boolean, holding only True or False, always written with a capital first letter. Example: passed = True.

The built-in function type() can be used to check the data type of any value, for example type(249.50) shows <class 'float'>.

5 What is indentation? Why is it important in Python?Indentation

Indentation is the blank space left at the beginning of a line to push it in from the left margin. In most languages indentation is only a matter of neatness, but in Python it is part of the syntax.

Python uses indentation to decide which statements belong to a block — the group of statements controlled by an if, elif, else, while or for. Statements indented by the same amount under the same header form one block.

marks = 80
if marks >= 33:
    print("Pass")
    print("Well done")
print("End of result")

The first two print() statements are indented, so they run only when the condition is True. The last one is not indented, so it always runs.

If the indentation is missing or uneven, Python reports an IndentationError and the program does not run. Four spaces per level is the usual convention, and tabs and spaces must never be mixed within one block.

6 Distinguish between the = and == operators with examples.Operators

= is the assignment operator. It stores the value on its right into the variable on its left. It does not ask a question and it produces no True or False result.

marks = 90        # stores 90 in marks

== is a relational (comparison) operator. It checks whether two values are equal and returns the Boolean value True or False.

print(marks == 90)   # displays True

A condition must compare, so writing if marks = 90: is invalid and raises a SyntaxError. The correct form is if marks == 90:.

7 Explain the range() function with examples, and state one difference between a for loop and a while loop.Loops

range() generates a sequence of whole numbers for a for loop to step through. It can be used in three forms.

  • range(stop) — begins at 0. range(5) gives 0, 1, 2, 3, 4.
  • range(start, stop)range(1, 6) gives 1, 2, 3, 4, 5.
  • range(start, stop, step)range(2, 11, 2) gives 2, 4, 6, 8, 10, and range(5, 0, -1) gives 5, 4, 3, 2, 1.

In every form the stop value is excluded, so counting 1 to 10 requires range(1, 11).

Difference: a for loop is used when the number of repetitions is known in advance and it manages the loop variable itself; a while loop is used when the number of repetitions depends on a condition, and the programmer must write the initialisation and the update. If the update is left out, a while loop becomes an infinite loop.

8 Write a Python program to check whether a number entered by the user is even or odd.Programs
# Program to check even or odd
n = int(input("Enter a number: "))
if n % 2 == 0:
    print(n, "is even")
else:
    print(n, "is odd")

Working: the % operator gives the remainder after division. A number divided by 2 leaves a remainder of 0 only when it is even, so the condition n % 2 == 0 separates the two cases. The int() around input() is necessary because input() returns a string and % cannot be applied to a string and a number.

Sample run: entering 14 prints 14 is even; entering 7 prints 7 is odd.

Previous-year board questions 6

Q1 Name the error produced by the following code and rewrite the corrected line: Marks = 80 followed by print(marks) 1 mark

Error: NameError — the name marks is not defined.

Reason: Python is case sensitive, so Marks and marks are two different variables.

Corrected line: print(Marks) (or rename the variable to marks on both lines).

Q2 Predict the output of the following code and justify your answer. A program assigns a = 15 and b = 4, then executes print(a / b), print(a // b) and print(a % b) on three separate lines. 2 marks

Output:

3.75
3
3

Justification: / is ordinary division and in Python 3 it always returns a float, giving 3.75. // is floor division, which discards the decimal part and gives the quotient 3. % gives the remainder when 15 is divided by 4, which is also 3. The two 3s are coincidence, not the same calculation.

Q3 Rewrite the following three lines after correcting all the errors, and underline each correction. Line 1 is n = input("Enter a number"). Line 2 is if n = 0 ; and line 3 is print("Zero") written at the left margin. 2 marks

There are four mistakes: the input is not converted to an integer, = is used instead of ==, the if line ends with a semicolon instead of a colon, and the body is not indented.

n = int(input("Enter a number: "))
if n == 0:
    print("Zero")

Corrections: (1) int() added around input() so that n is a number; (2) == used in the condition, since = only assigns; (3) a colon placed at the end of the if line in place of the semicolon; (4) the print() indented by four spaces.

Q4 Write a Python program that accepts the principal, rate and time from the user and displays the simple interest. 3 marks
# Program to calculate simple interest
p = float(input("Enter principal in rupees: "))
r = float(input("Enter rate of interest: "))
t = float(input("Enter time in years: "))
si = (p * r * t) / 100
print("Simple interest = Rs", si)

Points to include: float() is used rather than int() because a principal in rupees and a rate of interest can carry decimal parts; the formula is enclosed in parentheses so that the multiplication is completed before the division; and the result is displayed with a label rather than as a bare number.

Sample run: for a principal of 5000, a rate of 8 and a time of 2 years, the output is Simple interest = Rs 800.0.

Q5 Write a Python program that accepts the marks of three subjects, and displays the total, the average and the grade using if-elif-else: 90 and above Grade A, 75 to 89 Grade B, 60 to 74 Grade C, 33 to 59 Grade D, below 33 Grade E. 5 marks
# Program to find total, average and grade
m1 = int(input("Enter marks in subject 1: "))
m2 = int(input("Enter marks in subject 2: "))
m3 = int(input("Enter marks in subject 3: "))

total = m1 + m2 + m3
average = total / 3

print("Total =", total)
print("Average =", average)

if average >= 90:
    print("Grade A")
elif average >= 75:
    print("Grade B")
elif average >= 60:
    print("Grade C")
elif average >= 33:
    print("Grade D")
else:
    print("Grade E")

Explanation: each mark is read with int(input()) so that arithmetic is possible. The average is found with /, which returns a float — appropriate here, because an average is rarely a whole number. The conditions are arranged from the highest boundary downwards; if average >= 33 were tested first, every passing student would be given Grade D and the later branches would never run. The else has no condition and catches every remaining case.

Sample run: marks 80, 92 and 74 give Total = 246, Average = 82.0 and Grade B.

Q6 Write a Python program using a for loop to display the multiplication table of a number entered by the user, up to 10 terms. 3 marks
# Multiplication table
n = int(input("Enter a number: "))
for i in range(1, 11):
    print(n, "x", i, "=", n * i)

Explanation: range(1, 11) gives the values 1 to 10, because the stop value 11 is excluded — writing range(1, 10) is the common slip and prints only nine lines. The loop variable i is set automatically on each repetition, so no initialisation or update statement is needed. The commas inside print() place a single space between the items.

Sample output for 7: the first line is 7 x 1 = 7 and the last is 7 x 10 = 70.

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