Computer Science (Python) Chapter 5 4 Study Options Available

Getting Started with Python

CHAPTER PDF

Complete curriculum textbook chapter document for reading and offline study.

NOTES

Complete conceptual breakdown, formulas, diagrams, and memory aids.

Class 11 Computer Science | Chapter 5 – Getting Started with Python
Class XI · Computer Science · Chapter 5

Getting Started with Python

Complete learning notes with concept explanations, Python syntax, worked examples, practical programs, common errors and fully solved textbook exercises.

NCERT / Reprint 2026–27Python 3Mobile & Desktop Responsive

How to use these notes

Read each concept in sequence, type the code examples in Python 3, and compare your output with the displayed result. Code blocks are written for Python 3. The interactive prompt symbol >>> is used only when demonstrating Python Shell commands; remove it when writing a program in a .py file.

Learning objective: By the end of this chapter, you should be able to write small Python programs, choose appropriate data types, use operators and expressions, accept input, display output, convert data types and identify common program errors.

5.1 Introduction to Python

A program is an ordered set of instructions executed by a computer to perform a specific task. A programming language is the language used to write those instructions.

Computers fundamentally process machine instructions represented using binary digits 0 and 1. This is called machine language or a low-level language. Writing programs directly in binary is difficult for humans, so high-level languages such as Python, C++, Visual Basic, PHP and Java are used.

Source code and language translators

  • Source code: A program written in a high-level programming language.
  • Interpreter: Translates and executes program instructions progressively, commonly statement by statement. Execution stops if an error is encountered.
  • Compiler: Translates the source program as a whole into object code and can report errors found during compilation.

Interpreter – conceptual flow

Source program
      ↓
Interpreter
      ↓
Translate and execute
      ↓
Program output

Compiler – conceptual flow

Source program
      ↓
Compiler
      ↓
Object / machine code
      ↓
Execution

Python is introduced in this chapter as an interpreted, high-level language. The chapter uses Python 3.

5.1.1 Features of Python

  1. High-level language: Its syntax is comparatively easy for humans to read and write.
  2. Free and open source: It can be used without purchasing a language licence, and its source code is openly available.
  3. Interpreted language: Python programs are executed through a Python interpreter.
  4. Easy to understand: It has a clearly defined syntax and relatively simple structure.
  5. Case-sensitive: Uppercase and lowercase letters are treated differently. total, Total and TOTAL are different identifiers.
  6. Portable / platform independent: Python programs can run on different operating systems and hardware platforms when a suitable Python environment is available.
  7. Rich library: It provides many predefined modules and functions.
  8. Useful for web development: Python is used to develop web services and applications.
  9. Indentation: Indentation is used to define blocks and nested blocks of code.
Remember: Python is case-sensitive. Print() is not the same as print(). The standard output function is written in lowercase.

5.1.2 Working with Python

To write and execute Python programs, a Python interpreter must be installed on the computer, or an online Python interpreter may be used. The interpreter environment is also called the Python Shell.

The Python prompt >>> indicates that the interpreter is ready to accept a command.

>>> 10 + 20
30
>>> print("Welcome to Python")
Welcome to Python

Commands entered at the prompt are executed immediately. The official Python download website given in the textbook is python.org.

5.1.3 Execution Modes

Python provides two common ways to execute instructions: Interactive mode and Script mode.

A. Interactive Mode

Type a statement directly after the >>> prompt and press Enter. The interpreter executes it immediately and displays the result.

>>> a = 12
>>> b = 8
>>> a + b
20

Use: Testing a single statement, trying expressions and learning syntax.

Limitation: The entered statements are not automatically saved as a reusable program file; they may need to be typed again.

B. Script Mode

Write multiple Python statements in an editor, save the file with the .py extension, and execute the saved file.

# prog5_1.py
print("Save Earth")
print("Preserve Future")

Output:

Save Earth
Preserve Future

In IDLE, save the file and choose Run → Run Module. The output appears in the Python Shell.

Interactive modeScript mode
Executes statements directly at the prompt.Executes instructions saved in a .py file.
Useful for quick experiments.Suitable for complete and reusable programs.
Statements are not saved as a normal script automatically.Program can be saved, edited and executed again.

5.2 Python Keywords

Keywords are reserved words. Each keyword has a predefined meaning to the Python interpreter. A keyword must be used only for its intended purpose and cannot be used as an ordinary identifier.

The textbook's Python keyword table contains the following words (write them in the exact case shown):

False, None, True, and, as, assert, 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
# Invalid: 'if' is a reserved keyword
# if = 10

# Valid: use a meaningful non-keyword name
if_value = 10
print(if_value)

The list above follows the chapter's printed keyword table. Python releases can add keywords; in a current Python installation, keyword.kwlist can be used to inspect the interpreter's active keyword list.

5.3 Identifiers

An identifier is a user-defined name used to identify a variable, function or another program entity.

Rules for naming identifiers

  1. An identifier must begin with an uppercase letter, lowercase letter or underscore (_).
  2. After the first character, it may contain letters, digits and underscores.
  3. It cannot begin with a digit.
  4. It must not be a Python keyword.
  5. Spaces and special symbols such as !, @, #, $ and % are not allowed.
  6. It can be of any length, but short, meaningful names are preferred.
IdentifierValid?Reason
marks1YesBegins with a letter; digit appears later.
_totalYesMay begin with underscore.
1stRoomNoBegins with a digit.
Total MarksNoContains a space.
total-MarksNoContains a hyphen.
Hundred$NoContains a special symbol.
TrueNoBoolean keyword / reserved constant.
Total_MarksYesLetters and underscore only.

Meaningful identifiers

marks1 = 78
marks2 = 85
marks3 = 91
average = (marks1 + marks2 + marks3) / 3

length = 10
breadth = 5
area = length * breadth

Meaningful names such as average, length and breadth make a program easier to understand than unclear names such as a, b and c.

5.4 Variables

A variable is a name (identifier) that refers to an object/value stored in memory. A variable can refer to a string, number or another Python object. In Python, a variable is created when a value is assigned to it; a separate declaration statement is not required.

Assignment statement – syntax

variable_name = value

Examples

gender = 'M'
message = "Keep Smiling"
price = 987.9

print(message)
userNo = 101
print("User Number is", userNo)

Output:

Keep Smiling
User Number is 101

String values are enclosed in single or double quotation marks. Numeric values are written without quotation marks.

Example: Area of a rectangle

length = 10
breadth = 20
area = length * breadth
print(area)

Output: 200

Important: Assign a value to a variable before using it in an expression. Using an unassigned name generally produces a NameError.

5.5 Comments

Comments are explanatory remarks written in source code. They are ignored by the interpreter and do not affect program execution. They document the purpose, logic, input or output of a program and help other programmers maintain it.

Single-line comment syntax

# This is a comment
amount = 3400  # Total grocery spending

# Total marks in mathematics tests
totalMarks = test1 + test2 + finalTest

The hash symbol # marks the beginning of a comment; the rest of that line is treated as a comment.

Example: Sum of two numbers

# Program to find the sum of two numbers
num1 = 10
num2 = 20
result = num1 + num2
print(result)

Output: 30

Good practice: Comments should explain why a step is performed or clarify a non-obvious rule. Avoid writing so many comments that they make the program harder to read.

5.6 Everything is an Object

Python treats every value or data item—numeric, string or another type—as an object. An object can be assigned to a variable or passed to a function as an argument.

Every object has an identity during its lifetime. The built-in id() function returns an identity value for an object. It can be used to examine whether two names refer to the same object.

num1 = 20
print(id(num1))

num2 = 30 - 10
print(id(num2))
print(num1 is num2)

The textbook illustrates that two names may refer to the same object when they hold a reference to the same object. Exact identity numbers are implementation-dependent and can differ between executions.

OOP connection: In object-oriented programming, objects commonly represent entities such as students, employees, vehicles or books. They are often described in terms of data/attributes and behaviour/methods. Python supports object-oriented programming.

5.7 Data Types

A data type identifies the kind of value represented by an object and the operations that can be performed on it. Python's introductory data types in this chapter include numeric types, sequences, sets, None and dictionaries.

5.7.1 Number

Numeric data types store numerical values. The chapter classifies them into int, float and complex.

TypeMeaningExamples
intInteger numbers-12, -3, 0, 125
floatReal / floating-point numbers-2.04, 4.0, 14.23
complexComplex numbers, with real and imaginary parts3 + 4j, 2 - 2j
boolBoolean values True and FalseTrue, False

The Boolean type is a subtype of integer in Python. In Boolean contexts, zero is false and non-zero numeric values are true; empty strings and empty collections are also false.

Using type()

num1 = 10
num2 = -1210
flag = True
price = -1921.9
complex_num = -3 + 7.2j

print(type(num1))        # int
print(type(flag))        # bool
print(type(price))       # float
print(type(complex_num)) # complex

5.7.2 Sequence

A sequence is an ordered collection of items. Each item has an integer index. The chapter introduces strings, lists and tuples.

A. String (str)

A string is a group of characters. It may contain letters, digits, spaces or special characters. It is enclosed in single or double quotes.

str1 = 'Hello Friend'
str2 = "452"
print(str1)
print(type(str2))  # str

Even though "452" contains digits, it is a string and cannot be used directly as a number in arithmetic.

B. List (list)

A list is an ordered sequence of comma-separated items enclosed in square brackets []. Lists are mutable, so their elements can be changed.

list1 = [5, 3.4, "New Delhi", "20C", 45]
print(list1)
list1[0] = 10
print(list1)

C. Tuple (tuple)

A tuple is an ordered sequence of comma-separated items enclosed in parentheses (). Tuples are immutable after creation.

tuple1 = (10, 20, "Apple", 3.4, 'a')
print(tuple1)
print(tuple1[2])

5.7.3 Set

A set is an unordered collection of unique items, usually written inside curly brackets {}. Duplicate values are removed. A set is mutable as a collection, but its individual elements must be hashable; the chapter's description notes that elements cannot be changed in place.

set1 = {10, 20, 3.14, "New Delhi"}
set2 = {1, 2, 1, 3}
print(type(set1))
print(set2)  # duplicates are removed

Possible output for set2: {1, 2, 3}. Set display order is not guaranteed.

5.7.4 None

None is a special value representing the absence of a value. Its data type is NoneType. It is not the same as False or 0.

myVar = None
print(type(myVar))  # <class 'NoneType'>
print(myVar)        # None

5.7.5 Mapping – Dictionary

A dictionary stores information in key-value pairs. It is written using curly brackets. A colon separates each key from its value; commas separate pairs. Values are retrieved using their keys.

dict1 = {
    'Fruit': 'Apple',
    'Climate': 'Cold',
    'Price(kg)': 120
}
print(dict1)
print(dict1['Price(kg)'])  # 120

Keys are unique and commonly strings; values may be of different data types. Dictionary access is based on the key rather than a numeric position.

Choosing the right data type

RequirementSuitable typeReason
Marks that may changeListOrdered and modifiable collection.
Months of the year (fixed collection)TupleOrdered data that should not be changed.
Unique museum artefacts / unique entriesSetPrevents duplicate elements.
Phone book: name → numberDictionaryAssociates each key with a value.
Student's nameStringTextual information.

5.7.6 Mutable and Immutable Data Types

Mutable objects can be modified after creation. Immutable objects cannot be modified in place after creation. When a new value is assigned to a name referring to an immutable object, the name is made to refer to another object/value.

Mutable (chapter's classification)Immutable
Lists, sets, dictionariesIntegers, floats, Boolean values, complex numbers, strings, tuples, None

Understanding references and reassignment

num1 = 300
num2 = num1
print(num1, num2)

num1 = num2 + 100
print(num1, num2)

Initially both names refer to the value/object 300. The expression num2 + 100 produces 400; assigning it to num1 makes num1 refer to the new value, while num2 still refers to 300.

Mutable example: list

first = [10, 20]
second = first
second.append(30)
print(first)   # [10, 20, 30]

Both names refer to the same list object, so modifying the list through one reference is visible through the other.

Do not confuse reassignment with mutation: num1 = num1 + 1 reassigns an integer name; my_list.append(1) modifies an existing list object.

5.8 Operators

An operator performs a mathematical, comparison or logical operation. The values on which it operates are called operands. In 10 + num, the values 10 and num are operands and + is the operator.

5.8.1 Arithmetic Operators

OperatorOperationMeaning / example
+Addition5 + 6 → 11; also concatenates strings.
-Subtraction5 - 6 → -1
*Multiplication5 * 6 → 30; repeats a string by an integer.
/Division8 / 4 → 2.0
%ModulusRemainder: 13 % 5 → 3
//Floor division13 // 4 → 3
**Exponentiation3 ** 4 → 81
num1 = 13
num2 = 5
print(num1 + num2)  # 18
print(num1 - num2)  # 8
print(num1 * num2)  # 65
print(num1 / num2)  # 2.6
print(num1 % num2)  # 3
print(num1 // num2) # 2
print(num1 ** 2)    # 169

print("India" + "Hello") # IndiaHello
print("India" * 2)       # IndiaIndia

Important distinction: / performs true division; // performs floor division. For negative values, floor division rounds down towards negative infinity, so it is not always the same as simply removing decimal digits.

5.8.2 Relational (Comparison) Operators

Relational operators compare two operands and produce a Boolean result: True or False.

OperatorMeaningExample
==Equal to10 == 10 → True
!=Not equal to10 != 5 → True
>Greater than10 > 5 → True
<Less than3 < 5 → True
>=Greater than or equal to5 >= 5 → True
<=Less than or equal to4 <= 5 → True
num1 = 10
num2 = 0
num3 = 10
print(num1 == num3)  # True
print(num1 != num2)  # True
print(num1 > num2)   # True
print(num1 <= num3)  # True

Python also compares strings lexicographically (character by character using character code ordering). For example, "Good" > "Afternoon" evaluates to True because the first differing character determines the comparison.

5.8.3 Assignment Operators

Assignment operators assign a value to a variable or update its existing value.

OperatorEquivalent formExample if x=10, y=2
=Assignx = y → 2
+=x = x + y12
-=x = x - y8
*=x = x * y20
/=x = x / y5.0
%=x = x % y0
//=x = x // y5
**=x = x ** y100
num1 = 10
num2 = 2
num1 += num2
print(num1)  # 12

num1 -= num2
print(num1)  # 10

5.8.4 Logical Operators

Logical operators combine or reverse truth values. They are written in lowercase.

OperatorMeaningRuleExample
andLogical ANDTrue only when both operands are true.True and False → False
orLogical ORTrue when at least one operand is true.True or False → True
notLogical NOTReverses truth value.not True → False

Falsy values include False, None, numeric zero and empty collections such as "", (), [] and {}. Most other values are truthy.

age = 19
has_id = True
print(age >= 18 and has_id) # True
print(age < 18 or has_id)   # True
print(not has_id)           # False

5.8.5 Identity Operators

Identity operators check whether two names refer to the same object, not merely whether their values are equal.

OperatorMeaning
isTrue if both operands refer to the same object.
is notTrue if they do not refer to the same object.
num1 = 5
num2 = num1
print(num1 is num2)       # True
print(type(num1) is int) # True
Exam distinction: Use == to compare values. Use is to test object identity. For example, two different list objects can contain equal values but are not the same object.

5.8.6 Membership Operators

Membership operators check whether a value is present in a sequence or collection.

OperatorMeaningExample
inTrue if the value is found.2 in [1,2,3] → True
not inTrue if the value is not found.10 not in [1,2,3] → True
numbers = [1, 2, 3]
print(2 in numbers)      # True
print('2' in numbers)    # False: string is not integer
print(10 not in numbers) # True

5.9 Expressions

An expression is a combination of constants, variables and operators that evaluates to a value. A single value or standalone variable is also an expression. A standalone operator is not an expression.

Valid expression examples

  • 100
  • num
  • num - 20.4
  • 3.0 + 3.14
  • 23 / 3 - 5 * 7 * (14 - 2)
  • "Global" + "Citizen"

Expressions can be arithmetic, relational or logical. Python evaluates an expression and produces a result that can be printed, stored or used in another expression.

5.9.1 Precedence of Operators

Operator precedence determines the order in which operators are evaluated when an expression contains more than one kind of operator. Higher-precedence operators are evaluated before lower-precedence operators. Unary operators use one operand; binary operators use two operands.

Priority (high to low)OperatorsMeaning
1**Exponentiation
2~, unary +, unary -Complement, unary plus and minus
3*, /, %, //Multiplication, division, modulus, floor division
4+, -Addition and subtraction
5<=, <, >, >=, ==, !=Comparisons
6Assignment operatorsAssignment / augmented assignment
7is, is notIdentity
8in, not inMembership
9notLogical NOT
10andLogical AND
11orLogical OR

Parentheses override normal precedence: the expression inside () is evaluated first. Operators of equal precedence are generally evaluated left to right, except where Python's associativity rules specify otherwise (notably exponentiation).

Worked examples

Example 1: 20 + 30 * 40

= 20 + (30 * 40)
= 20 + 1200
= 1220

Multiplication has higher precedence than addition.

Example 2: 20 - 30 + 40

= (20 - 30) + 40
= -10 + 40
= 30

Addition and subtraction have equal precedence, so evaluation proceeds from left to right.

Example 3: (20 + 30) * 40

= 50 * 40
= 2000

Parentheses force addition to happen first.

Example 4: 15.0 / 4 + (8 + 3.0)

= 15.0 / 4 + 11.0
= 3.75 + 11.0
= 14.75

5.10 Statement

A statement is a unit of code that the Python interpreter can execute. An assignment statement stores a value in a variable; a print statement displays values.

x = 4              # Assignment statement
cube = x ** 3      # Assignment statement
print(x, cube)     # Print statement

Output: 4 64

Expressions produce values; statements perform an instruction. An expression can form part of a statement.

5.11 Input and Output

Input using input()

The input() function accepts information typed by the user. The function returns the entered data as a string, even if the user types digits.

Syntax

variable = input("Prompt message")

The prompt is optional. The user presses Enter to finish entering the value.

fname = input("Enter your first name: ")
age = input("Enter your age: ")
print(fname)
print(type(age))

If the user enters Arnab and 19, then fname is the string "Arnab" and age is the string "19".

Accepting a numeric value

age = int(input("Enter your age: "))
print(type(age))  # <class 'int'>

Here the entered text is converted to an integer. If the user enters text that cannot be converted to an integer, Python raises a ValueError.

Output using print()

The print() function displays output on the standard output device, usually the screen. It evaluates the supplied expressions, displays their values and moves to a new line by default.

Syntax

print(value1, value2, ..., sep=' ', end='\\n')
  • sep: Optional separator inserted between multiple values. Default is a space.
  • end: Optional string appended after the final value. Default is a newline (\n).
print("Hello")
print(10 * 2.5)
print("I" + "love" + "my" + "country")
print("I'm", 16, "years old")
print("A", "B", "C", sep="-")
print("Hello", end=" ")
print("World")

Output:

Hello
25.0
Ilovemycountry
I'm 16 years old
A-B-C
Hello World
Plus vs comma in print(): + concatenates strings and generally requires compatible operand types. Commas pass separate arguments to print(), which can display values of different types and inserts the separator (space by default).

5.12 Type Conversion

Type conversion means changing a value from one data type to another. It is useful when processing user input or combining values of different types.

Example: if a user enters 2, the expression num1 * 2 produces "22" when num1 is the string "2", because * repeats strings. Convert the input to an integer to obtain the numerical result 4.

num1 = input("Enter a number: ")
num1 = int(num1)
num1 = num1 * 2
print(num1)

5.12.1 Explicit Conversion (Type Casting)

Explicit conversion occurs when the programmer directly instructs Python to convert a value. General form:

new_value = new_data_type(expression)
FunctionPurposeExample
int(x)Converts a suitable value to integer.int("25") → 25
float(x)Converts a suitable value to float.float("2.5") → 2.5
str(x)Converts a value to string representation.str(70) → "70"
chr(x)Returns the character for an integer code point (the textbook describes ASCII).chr(65) → "A"
ord(x)Returns the integer code point of a one-character string (the textbook describes ASCII).ord("A") → 65

Integer to float

num1 = 10
num2 = 20
num3 = num1 + num2
print(num3, type(num3))

num4 = float(num1 + num2)
print(num4, type(num4))

Output: 30 <class 'int'> and 30.0 <class 'float'>.

Float to integer

num1 = 10.2
num2 = 20.6
total = num1 + num2
print(total)          # 30.8
print(int(total))     # 30

Converting a float to an integer using int() discards the fractional part; it does not round to the nearest integer.

Number to string

priceIcecream = 25
priceBrownie = 45
totalPrice = priceIcecream + priceBrownie
print("The total in Rs." + str(totalPrice))

Output: The total in Rs.70.

String to integer before addition

icecream = '25'
brownie = '45'

price_text = icecream + brownie
print("Text concatenation:", price_text)  # 2545

price_number = int(icecream) + int(brownie)
print("Numeric total:", price_number)     # 70
Possible information loss: Explicit conversion may lose information. For example, int(20.67) returns 20; the fractional part is discarded. Also, int("3.14") raises an error because the string is not an integer-form string.

5.12.2 Implicit Conversion (Coercion)

Implicit conversion occurs automatically when Python converts a value to another compatible type during an operation. For example, when an integer and a float are added, Python promotes the integer to a float so the result can preserve the fractional type.

num1 = 10       # int
num2 = 20.0     # float
sum1 = num1 + num2
print(sum1)       # 30.0
print(type(sum1)) # <class 'float'>

This is called type promotion. Python uses a wider compatible type where appropriate rather than automatically discarding the fractional part.

5.13 Debugging

Debugging is the process of identifying and removing bugs (errors) from a program. A program may fail to execute or may execute but produce an incorrect result. The chapter classifies errors into three types.

5.13.1 Syntax Errors

A syntax error occurs when code violates the grammar rules of Python. The interpreter cannot correctly interpret the statement and reports an error.

# Syntax error: missing closing parenthesis
print(10 + 12

# Correct statement
print(10 + 12)

Other common examples include a missing colon after a block header, incorrect quotation marks or invalid indentation in a block.

5.13.2 Logical Errors

A logical error occurs when the program runs but the logic is incorrect, so it produces an undesired output. It may be difficult to identify because no execution-stopping error is necessarily shown.

Example: Incorrect average

# Incorrect
average = 10 + 12 / 2
print(average)  # 16.0

# Correct
average = (10 + 12) / 2
print(average)  # 11.0

The incorrect version divides 12 by 2 before adding 10 because of operator precedence. Parentheses correct the logic.

5.13.3 Runtime Errors

A runtime error occurs while a program is executing. The statement may be syntactically correct, but the operation cannot be completed for the supplied data or current situation.

num1 = 10.0
num2 = int(input("num2 = "))
print(num1 / num2)

This program works when the user enters a non-zero integer. It can raise a ValueError if the input cannot be converted to an integer, or a ZeroDivisionError if the user enters zero.

Comparison of error types

ErrorWhen it occursTypical exampleEffect
SyntaxCode is not written according to Python syntax.Missing ) or colon.Program cannot proceed normally.
LogicalProgram runs with incorrect logic.Wrong average formula.Incorrect output.
RuntimeDuring execution.Division by zero; invalid conversion.Abnormal termination unless handled.

Practical debugging method

  1. Read the complete error message and identify the line number.
  2. Check spelling, brackets, quotation marks, colons and indentation.
  3. Check that variables have been assigned values before use.
  4. Trace calculations manually and verify operator precedence.
  5. Test boundary values, zero values and unexpected user input.
  6. Run the program again after making one correction at a time.

Chapter Summary & Quick Revision

  • Python is a free, open-source, high-level, interpreted language.
  • Python is case-sensitive and uses indentation to define code blocks.
  • Interactive mode executes commands immediately; script mode runs saved .py files.
  • Keywords are reserved words. Identifiers are user-defined names that follow naming rules.
  • Variables are created through assignment and must be assigned before use.
  • Comments begin with # and are not executed.
  • Python treats values as objects; id() returns an object's identity.
  • Data types covered include integer, float, complex, Boolean, string, list, tuple, set, None and dictionary.
  • Lists, sets and dictionaries are mutable; strings, tuples and numeric types are immutable.
  • Operators manipulate operands. Main categories include arithmetic, relational, assignment, logical, identity and membership.
  • Expressions combine values, variables and operators and evaluate to a value.
  • input() accepts user input as a string; print() displays output.
  • Type conversion may be explicit or implicit.
  • Debugging identifies and removes syntax, logical and runtime errors.

Common examination mistakes

  • Writing = instead of == for comparison.
  • Assuming input() returns an integer automatically.
  • Confusing is (identity) with == (value equality).
  • Forgetting that strings need quotes and identifiers cannot contain spaces.
  • Ignoring operator precedence or missing parentheses in a formula.
  • Assuming int(20.9) rounds to 21; it returns 20.
  • Using a variable before assigning a value.

Textbook Exercise – Complete Solutions (Questions 1–21)

Solutions below follow the question wording and concepts in the supplied chapter. For output questions, assume the values specified in the question. Where the question itself contains an unassigned variable, the resulting error is explained rather than inventing a value.

Q1. Which identifier names are invalid and why?

NameValid?Reason
i. Serial_no.NoContains a period.
ii. 1st_RoomNoBegins with a digit.
iii. Hundred$NoContains $.
iv. Total MarksNoContains a space.
v. Total_MarksYesLetters and underscore are allowed.
vi. total-MarksNoHyphen is not allowed in an identifier.
vii. _PercentageYesAn identifier may begin with underscore.
viii. TrueNoReserved Boolean constant / keyword.

Q2. Write the corresponding assignment statements.

# (a)
length = 10
breadth = 20

# (b) Average of length and breadth
sum = (length + breadth) / 2

# (c) List of stationery items
stationery = ['Paper', 'Gel Pen', 'Eraser']

# (d) Name components
first = 'Mohandas'
middle = 'Karamchand'
last = 'Gandhi'

# (e) Full name with spaces
fullname = first + ' ' + middle + ' ' + last
print(fullname)

Output: Mohandas Karamchand Gandhi. The variable name sum is used because the exercise specifies it, although in larger programs it is usually better not to reuse the name of a built-in function.

Q3. Write logical expressions and evaluate them.

  1. Sum of 20 and −10 is less than 12: (20 + (-10)) < 12 → True (10 < 12).
  2. num3 is not more than 24: num3 <= 24.
  3. 6.75 is between num1 and num2: (num1 < 6.75 < num2) or (num2 < 6.75 < num1). This works regardless of which integer is smaller.
  4. middle is larger than first and smaller than last: first < middle < last (lexicographic string comparison).
  5. List stationery is empty: len(stationery) == 0 or not stationery.

For (b)–(e), the exact True/False result depends on the values already stored in the named variables.

Q4. Add parentheses so each expression evaluates to True.

(a) 0 == (1 == 2)
    # 1 == 2 is False; 0 == False is True

(b) 2 + (3 == 4) + 5 == 7
    # 3 == 4 is False (numeric value 0)
    # 2 + 0 + 5 == 7 → True

(c) (1 < -1) == (3 > 4)
    # False == False → True

Q5. Write the output of the following.

(a)

num1 = 4
num2 = num1 + 1
num1 = 2
print(num1, num2)

Output: 2 5. num2 receives 5 before num1 is changed to 2.

(b)

num1, num2 = 2, 6
num1, num2 = num2, num1 + 2
print(num1, num2)

Output: 6 4. The right-hand expressions are evaluated before the assignments are made.

(c)

num1, num2 = 2, 3
num3, num2 = num1, num3 + 1
print(num1, num2, num3)

Result: NameError because num3 is used on the right-hand side before it has been assigned a value. The assignment does not first create num3; the right-hand side must be evaluated first.

Q6. Which data type is suitable and why?

Data valueSuitable typeReason
(a) Number of months in a yearintWhole-number count (12).
(b) Resident of Delhi or notboolOnly True / False.
(c) Mobile numberstrIdentifier-like digits; arithmetic is not required and leading zeroes may matter.
(d) Pocket moneyfloat or intAmount may include a fractional currency value; choose according to precision required.
(e) Volume of a spherefloatMay contain a fractional value.
(f) Perimeter of a squarefloat or intDepends on whether side length is fractional or whole.
(g) Name of studentstrText data.
(h) Address of studentstrText containing words, digits and symbols.

Q7. Give the output when num1=4, num2=3, num3=2.

PartExpression / calculationOutput
anum1 += num2 + num3 → 4 + 3 + 29
b4 ** (3 + 2) = 4 ** 51024
cnum1 **= num2 + num3 → 4 ** 5num1 becomes 1024
d'5' + '5' (string concatenation)55 as a string
e4.00 / (2.0 + 2.0)1.0
f2 + 9 * ((3*12)-8) / 10 = 2 + 25.227.2
g24 // 4 // 2 = 6 // 23
hfloat(10)10.0
iint('3.14')ValueError
j'Bye' == 'BYE'False
k10 != 9 and 20 >= 20True
l34 != -1 and 29 >= 29/9True
m15 < 50 and 29 <= 29True
n(0 < 6) or (not(10 == 6) and (10 < 0))True

For (c), if each sub-question is run independently with the given initial values, num1 becomes 1024; the statement itself has no print call.

Q8. Categorise as syntax, logical or runtime error.

(a) 25 / 0 – Runtime error (ZeroDivisionError) when evaluated.

(b) num1 = 25; num2 = 0; num1/num2 – Runtime error for division by zero. Both snippets are syntactically valid.

Q9. Dartboard radius 10, centre (0,0).

A point lies on or inside a circle when its distance from the centre is at most the radius. Squaring both sides gives:

x**2 + y**2 <= 10**2
CoordinatesCalculationInside?
(a) (0,0)0² + 0² = 0 ≤ 100True
(b) (10,10)100 + 100 = 200 > 100False
(c) (6,6)36 + 36 = 72 ≤ 100True
(d) (7,8)49 + 64 = 113 > 100False
x = 6
y = 6
print(x**2 + y**2 <= 100)

Q10. Convert Celsius to Fahrenheit.

Formula: F = C × 9/5 + 32.

celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = celsius * 9 / 5 + 32
print("Temperature in Fahrenheit:", fahrenheit)

print("Boiling point:", 100 * 9 / 5 + 32, "F")
print("Freezing point:", 0 * 9 / 5 + 32, "F")

Boiling point: 212°F. Freezing point: 32°F.

Q11. Calculate amount payable using simple interest.

Formula: SI = (P × R × T) / 100; Amount = Principal + SI.

P = float(input("Enter principal: "))
R = float(input("Enter annual rate (%): "))
T = float(input("Enter time in years: "))

SI = (P * R * T) / 100
amount = P + SI

print("Simple Interest:", SI)
print("Amount payable:", amount)

Q12. Calculate days taken by A, B and C working together.

Given formula: xyz / (xy + yz + xz).

x = float(input("Days taken by A: "))
y = float(input("Days taken by B: "))
z = float(input("Days taken by C: "))

denominator = x*y + y*z + x*z
days = (x*y*z) / denominator

print("Days required together:", days)

Each input must be a positive number of days; the denominator must not be zero.

Q13. Enter two integers and perform all arithmetic operations.

a = int(input("Enter first integer: "))
b = int(input("Enter second integer: "))

print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
print("Modulus:", a % b)
print("Floor division:", a // b)
print("Exponentiation:", a ** b)

For division, modulus and floor division, b must not be zero.

Q14. Swap two numbers using a third variable.

a = int(input("Enter a: "))
b = int(input("Enter b: "))

temp = a
a = b
b = temp

print("After swapping:", a, b)

Logic: Store the first value safely in temp, copy the second value into the first variable, then copy the saved first value into the second.

Q15. Swap two numbers without a third variable.

a = int(input("Enter a: "))
b = int(input("Enter b: "))

a, b = b, a

print("After swapping:", a, b)

Python evaluates the right-hand side first and then assigns the values to the left-hand variables. This is the clearest Python approach.

Q16. Repeat the string “GOOD MORNING” n times.

n = int(input("Enter number of repetitions: "))
message = "GOOD MORNING"
print(message * n)

For n = 3, the repeated text appears three times consecutively. If spaces or separate lines are required, use print((message + "\\n") * n).

Q17. Find the average of three numbers.

num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))

average = (num1 + num2 + num3) / 3
print("Average:", average)

Q18. Find sphere volume for radii 7 cm, 12 cm and 16 cm.

Formula: V = (4/3) × π × r³.

import math

radii = [7, 12, 16]
for r in radii:
    volume = (4 / 3) * math.pi * r**3
    print("Radius:", r, "cm")
    print("Volume:", volume, "cm^3")

Approximate volumes: r=7 → 1436.76 cm³; r=12 → 7238.23 cm³; r=16 → 17157.28 cm³.

Q19. Ask for name and age; show the year the user turns 100.

from datetime import date

name = input("Enter your name: ")
age = int(input("Enter your age: "))

current_year = date.today().year
year_turn_100 = current_year + (100 - age)

print(name, "will turn 100 in the year", year_turn_100)

This solution uses the current calendar year at the time the program is run. It assumes the age entered is the user's current age in completed years; the exact birthday can affect the precise date.

Q20. Calculate energy using E = mc².

Speed of light c ≈ 3 × 10⁸ m/s.

mass = float(input("Enter mass in kg: "))
c = 3 * 10**8
energy = mass * c**2

print("Equivalent energy:", energy, "joules")

Q21. Calculate ladder height against a wall.

If the ladder length is the hypotenuse and the angle is measured from the ground, height = length × sin(angle). Python's trigonometric functions use radians, so convert degrees using math.radians().

import math

length = float(input("Enter ladder length in feet: "))
angle = float(input("Enter angle in degrees: "))

height = length * math.sin(math.radians(angle))
print("Height reached:", height, "feet")
LengthAngleHeight (approx.)
16 ft75°15.45 ft
20 ft0°0 ft
24 ft45°16.97 ft
24 ft80°23.64 ft

Case Study – Student Management Information System (SMIS)

Schools use a Student Management Information System to record and manage student information. The chapter identifies these functions:

  • Recording and maintaining students' personal details.
  • Maintaining assessment marks and computing results.
  • Keeping track of student attendance.
  • Managing other student-related data.

Suggested input fields

Use the details printed on a school identity card, for example admission/roll number, student's name, class, section, date of birth and contact details where appropriate. The exact fields should match the school's own ID card and data policy.

Sample Python program

# Student Information Entry – simple classroom example
student_name = input("Enter student name: ")
admission_no = input("Enter admission number: ")
class_name = input("Enter class: ")
section = input("Enter section: ")

print("\\nSTUDENT DETAILS")
print("------------------------------")
print("Name          :", student_name)
print("Admission No. :", admission_no)
print("Class         :", class_name)
print("Section       :", section)

This is a basic console demonstration of accepting and displaying one student's details. A complete school information system would require structured storage, validation, access control and additional modules; those implementation details are beyond this chapter's exercise.

Documentation Tips

Well-documented programs are easier to read, understand, maintain and extend. The chapter provides the following checklist:

  • Clearly state the objective of the program at the beginning.
  • Mention the objective of each function at the beginning of that function.
  • Insert comments at suitable places to improve readability; avoid over-commenting.
  • Use meaningful and appropriate variable and function names.
  • Avoid unnecessary single-letter variable names.
  • Choose a meaningful program filename, such as bankingProject.py for a banking program, rather than naming the file after the programmer.
  • Indent the program code properly.
  • Use consistent naming conventions throughout the program, such as firstNum or first_num.
  • Review a peer's program and provide constructive feedback to improve its documentation.
Final practical checklist: Before submitting a Python program, verify its objective, meaningful names, comments, indentation, consistent naming style, correct output and behaviour for invalid or boundary inputs.
Class XI Computer Science · Chapter 5: Getting Started with Python · Study notes prepared from the supplied textbook PDF (Reprint 2026–27).

TEXTBOOK SOLUTION

Step-by-step solved textbook exercises, derivations, and solutions.

Exercise Solutions Being Updated

Step-by-step verified exercise solutions are currently being uploaded.

IMPORTANT QUESTION

High-yield board questions, previous year questions (PYQs), and model answer keys.

Important Questions Being Compiled

Board blueprint and previous years' exam questions for this chapter will be live soon.