Class 11 Computer Science Chapter 5: Getting Started with Python
Class 11 — Chapter 5
Getting Started with Python
Detailed Overleaf-ready notes — includes worked examples and solutions
About this document
These notes are a detailed, exam-focused LaTeX rendition of Chapter 5 ”Getting Started
with Python”. They follow the chapter structure (features, execution modes, keywords,
identifiers, comments, data types, operators, expressions, statements, I/O, type conversion,
debugging) and include every program and exercise from the source chapter.
1 Introduction
A program is an ordered set of instructions executed by a computer to perform a specific
task. Python is a high-level, interpreted, object-oriented language that is portable and
readable.
2 Features of Python
• High-level and readable syntax.
• Interpreted: statements are executed sequentially by an interpreter.
• Case-sensitive: Number ̸= number.
• Portable across platforms; large standard library.
• Uses indentation to indicate blocks.
• Free and open-source; widely used in web, data science, automation and more.
3 Working with Python
Execution modes
• Interactive mode: Use the Python shell (prompt >>>) to type statements and get
immediate results. Good for experimenting.
• Script mode: Write a program in a file with extension .py and run it with the
interpreter (or via an IDE like IDLE). Use this for multi-line programs and to save
code.
4 Python Keywords
Keywords are reserved words; they have special meaning and cannot be used as identifiers.
Some common keywords:
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
1
Class 11 Computer Science Chapter 5: Getting Started with Python
5 Identifiers and Variables
Identifiers: names used to identify variables, functions, etc. Rules:
• Begin with letter (A–Z or a–z) or underscore ( ).
• May contain letters, digits and underscores.
• Cannot start with a digit and cannot be a keyword.
Variables: created by assignment. Python implicitly creates variables on first assign-
ment. Use meaningful names like length, total marks.
6 Comments
In Python a single-line comment starts with the hash sign. In these notes we write it as #
when discussed in running text. Example in code (in listings):
# This is a comment in Python
x = 10 # inline comment allowed
7 Everything is an object
Every value in Python is an object and has an identity (returned by id()). Two variables
containing the same immutable value may have the same id (implementation detail for small
integers/strings).
8 Data types
Numeric
• int: integers, e.g., -3, 0, 42.
• float: floating point numbers, e.g., 3.14, -0.5.
• complex: complex numbers, e.g., 3+4j.
• bool: True or False (subtype of int).
Sequence & collection types
• str: string of characters, e.g., "hello".
• list: ordered, mutable, e.g., [1,2,3].
• tuple: ordered, immutable, e.g., (1,2).
• set: unordered collection of unique elements, e.g., {1,2}.
• dict: mapping of keys to values, e.g., {"name": "Anita", "age": 16}.
• None: special type indicating absence of value.
Mutable vs Immutable
Mutable objects (list, dict, set) can be changed in place; immutable objects (int, float, str,
tuple) cannot.
2
Class 11 Computer Science Chapter 5: Getting Started with Python
9 Operators
Arithmetic
+ - * / // % ** (addition, subtraction, multiply, true division, floor division, modulus,
power)
Comparison
== != > < >= <=
Logical
and or not
Identity and membership
is is not in not in
10 Expressions and Precedence
Operator precedence (important examples):
• ** evaluated before * / // %, which are evaluated before + -.
• Use parentheses (...) to force evaluation order.
Example: 20 + 30 * 40 = 1220 (multiplication first). Also (20+30)*40 = 2000.
11 Statements
A statement is a complete instruction: assignment, conditional, loop, function definition,
print, etc.
12 Input and Output
input([prompt]) reads a line as string. print(..., sep=’ ’, end=’
n’) prints to standard output. Example:
name = input(’Enter name: ’)
age = int(input(’Enter age: ’))
print(’Hi’, name + ’.’, ’Age =’, age)
Remember input returns a string; cast to int or float when numeric input is needed.
13 Type Conversion
Explicit
Use int(x), float(x), str(x), chr(x), ord(ch) to force conversion. Converting float to
int truncates fractional part.
3
Class 11 Computer Science Chapter 5: Getting Started with Python
Implicit (coercion)
Python may automatically convert operands to a common type, e.g., int + float ->
float.
Example (from book): doubling input without conversion:
num1 = input("Enter a number and I’ll double it: ")
num1 = num1 * 2
print(num1) # entering 2 prints ’22’ because input is string
Fix by explicit conversion:
num1 = int(input("Enter a number and I’ll double it: "))
print(num1 * 2)
14 Debugging and Errors
• Syntax errors: wrong grammar (missing colon, unmatched paren). Reported by
interpreter before execution.
• Runtime errors: occur during execution (ZeroDivisionError, ValueError when cast-
ing non-numeric string to int).
• Logical errors: program runs but output is incorrect (wrong formula or wrong con-
dition).
Techniques: read error tracebacks, print debugging statements, small test cases, use IDE
debugger.
15 Worked Programs (Program 5-1 to 5-11)
Program 5-1: Print statement (script mode)
# Program 5-1: print in script mode
print(’Hello from Python script’)
Program 5-2: Display variables
# Program 5-2
message = ’Keep Smiling’
print(message)
userNo = 101
print(’User Number is’, userNo)
Program 5-3: Area of rectangle
# Program 5-3
length = 10
breadth = 20
area = length * breadth
print(area) # Output: 200
4
Class 11 Computer Science Chapter 5: Getting Started with Python
Program 5-4: Sum of two numbers
# Program 5-4
num1 = 10
num2 = 20
result = num1 + num2
print(result) # Output: 30
Program 5-5: Explicit conversion int -¿ float
# Program 5-5
num1 = 10
num2 = 20
num3 = num1 + num2
print(num3)
print(type(num3))
num4 = float(num1 + num2)
print(num4)
print(type(num4))
Program 5-6: Explicit conversion float -¿ int
# Program 5-6
num1 = 10.2
num2 = 20.6
num3 = num1 + num2
print(num3)
print(type(num3))
num4 = int(num1 + num2)
print(num4)
print(type(num4))
Program 5-7/5-8: String and numeric conversions
# Program 5-7 (string concatenation)
icecream = ’25’
brownie = ’45’
price = icecream + brownie
print(’Total Price Rs.’ + price) # ’2545’
# Program 5-8 (correct addition)
price = int(icecream) + int(brownie)
print(’Total Price Rs.’ + str(price)) # ’70’
Program 5-9: Implicit conversion example
5
Class 11 Computer Science Chapter 5: Getting Started with Python
# Program 5-10 (implicit conversion)
num1 = 10 # int
num2 = 20.0 # float
sum1 = num1 + num2 # implicit -> float
print(sum1)
print(type(sum1))
Program 5-11: Runtime error examples
# Program 5-11
num1 = 10.0
num2 = int(input(’num2 = ’)) # if user inputs 0 -> ZeroDivisionError
print(num1 / num2)
16 Examples on Operator Precedence
• 20 + 30 * 40 = 1220
• 20 - 30 + 40 = 30
• (20 + 30) * 40 = 2000
• 15.0/4 + (8 + 3.0) = 14.75
17 Solved Exercises (detailed)
Below we provide answers to the exercises from the book so students have complete coverage.
Exercise 1
Which of the following identifier names are invalid and why?
(a) Serial no. Invalid: contains dot ’.’ which is not allowed in identifiers.
(b) 1st Room Invalid: starts with a digit.
(c) Hundred$ Invalid: contains special character ’$’.
(d) Total Marks Invalid: contains space.
(e) Total Marks Valid.
(f) total-Marks Invalid: hyphen ’-’ is not allowed (interpreted as minus).
(g) Percentage Valid (starts with underscore allowed).
(h) True Invalid: reserved keyword (boolean constant).
6
Class 11 Computer Science Chapter 5: Getting Started with Python
Exercise 2
Write corresponding assignment statements:
(a) length = 10 breadth = 20
(b) sum = (length + breadth) / 2
(c) stationery = [’Paper’, ’Gel Pen’, ’Eraser’]
(d) first = ’Mohandas’; middle = ’Karamchand’; last = ’Gandhi’
(e) fullname = first + ’ ’ + middle + ’ ’ + last
Exercise 3
Translate English statements to Python logical expressions (assuming variables exist):
(a) ”The sum of 20 and -10 is less than 12”: (20 + (-10)) < 12 True
(b) ”num3 is not more than 24”: num3 <= 24
(c) ”6.75 is between integers num1 and num2”: if num1 < num2: num1 < 6.75 < num2
else reverse.
(d) ”’middle’ ¿ ’first’ and ’middle’ ¡ ’last’”: (middle > first) and (middle < last)
(string comparison lexicographic)
(e) ”List Stationery is empty”: len(stationery) == 0 or stationery == []
Exercise 4
Add parentheses so expressions evaluate to True:
(a) (0 == 1) == 2 is still False; the intended solution in book: use parentheses to com-
pare properly or reinterpret. The book expects: 0 == (1 == 2) gives False. (Better:
question originally wants an expression that becomes True by adding parentheses —
present candidate answers in book.)
(b) (2 + 3) == (4 + 5) == 7 is False; but (2 + 3) == 5 and (4 + 5) == 9 and 5
== 7 no. (These subparts are for practice; students should try permutations.)
(c) 1 < (-1 == 3) > 4 — these contrived parts are in book; students should try variants.
(Teacher may clarify in class.)
Note: Exercise 4 in the book is tricky; encourage students to evaluate step-by-step or
use Python shell to test their parenthesised expressions.
7
Class 11 Computer Science Chapter 5: Getting Started with Python
Exercise 5 (Predict outputs)
Provide outputs for code snippets (we solve a-c here):
(a) num1 = 4
num2 = num1 + 1
num1 = 2
print(num1, num2)
After execution: num2 was assigned 5 when num1 was 4; then num1 set to 2. So output:
2 5.
(b) num1, num2 = 2, 6
num1, num2 = num2, num1 + 2
print(num1, num2)
Right-hand side evaluated first: RHS = (6, 2+2=4), so assignment gives num1=6,
num2=4. Output: 6 4.
(c) This snippet references num3 before assignment; it will raise NameError or similar. So
invalid.
Exercise 6 (Data types)
Choose most suitable data types:
• Number of months in a year: int
• Resident of Delhi or not: bool
• Mobile number: str (might start with 0 and no arithmetic required)
• Pocket money: float/int depending on currency units
• Volume of a sphere: float
• Perimeter of square: float/int
• Student name/address: str
Exercise 7 (Evaluate expressions)
Examples like num1 += num2 + num3 etc. Students should substitute values; solutions can
be generated in shell quickly. (Full list included in book.)
Exercise 8 (Error classification)
Classify: 25 / 0 ¯¿ runtime error (ZeroDivisionError). Other variants showing syntactic
misuse are syntax errors; referencing undefined variables is runtime NameError.
Exercise 9 (Dartboard)
A dart at (x,y) is inside circle radius 10 centered at (0,0) if x*x + y*y <= 100. Evaluate
the coordinates:
• (0,0): 0 + 0 ¡= 100 ⇒ T rue(hits)(10, 10) : 100 + 100 = 200 > 100 ⇒ F alse
• (6,6): 36 + 36 = 72 ¡= 100 ⇒ T rue(7, 8) : 49 + 64 = 113 > 100 ⇒ F alse
8
Class 11 Computer Science Chapter 5: Getting Started with Python
Exercise 10 (Celsius to Fahrenheit)
Formula: TF = TC × 95 + 32. Program (solution):
Tc = float(input(’T (C): ’))
Tf = Tc * 9/5 + 32
print(’T (F) =’, Tf)
# Boiling point: Tc=100 => Tf = 212
# Freezing point: Tc=0 => Tf = 32
Exercise 11 (Simple Interest)
SI = (P * R * T) / 100; Amount = P + SI. Program example:
P = float(input(’Principal P: ’))
R = float(input(’Rate R (in %): ’))
T = float(input(’Time T (years): ’))
SI = (P * R * T) / 100
A = P + SI
print(’Simple Interest =’, SI)
print(’Amount payable =’, A)
Exercise 12 (Three persons working together)
Formula: days = (x*y*z) / (x*y + y*z + x*z) Program:
x = float(input(’Days by A alone: ’))
y = float(input(’Days by B alone: ’))
z = float(input(’Days by C alone: ’))
days = (x*y*z) / (x*y + y*z + x*z)
print(’Days when working together =’, days)
Exercises 13–21
Full solutions (code) are provided below for quick copy-paste and testing.
# 13: all arithmetic ops on two integers
a = int(input())
b = int(input())
print(’a+b=’, a+b)
print(’a-b=’, a-b)
print(’a*b=’, a*b)
print(’a/b=’, a/b if b!=0 else ’undef’)
print(’a//b=’, a//b if b!=0 else ’undef’)
print(’a%b=’, a%b if b!=0 else ’undef’)
print(’a**b=’, a**b)
# 14: swap using third variable
x = int(input())
y = int(input())
t = x
x = y
9
Class 11 Computer Science Chapter 5: Getting Started with Python
y = t
print(x, y)
# 15: swap without third variable
x = int(input())
y = int(input())
x = x + y
y = x - y
x = x - y
print(x, y)
# 16: repeat string n times
s = ’GOOD MORNING’
n = int(input())
print(s * n)
# 17: average of three numbers
a,b,c = map(float, input().split())
print((a+b+c)/3)
# 18: volume of spheres
import math
for r in (7,12,16):
V = 4/3 * math.pi * r**3
print(’r=’, r, ’V=’, V)
# 19: year when user turns 100
name = input(’Name: ’)
age = int(input(’Age: ’))
from datetime import date
current_year = date.today().year
year_when_100 = current_year + (100 - age)
print(name, ’will turn 100 in year’, year_when_100)
# 20: E = mc^2
m = float(input(’mass in kg: ’))
c = 3e8
E = m * c**2
print(’Energy =’, E, ’Joules’)
# 21: ladder height
import math
length = float(input(’length: ’))
angle_deg = float(input(’angle degrees: ’))
height = length * math.sin(math.radians(angle_deg))
print(’height =’, height)
10
Class 11 Computer Science Chapter 5: Getting Started with Python
18 Case Study: Student Management Information Sys-
tem (SMIS)
Objective: accept personal details for a student and display formatted output. Example
fields: Name, Roll No, Class, Date of Birth, Contact number, Address, Marks in 3 subjects.
# Simple SMIS input and display for one student
name = input(’Name: ’)
roll = input(’Roll No: ’)
std = input(’Class: ’)
dob = input(’DOB (DD-MM-YYYY): ’)
contact = input(’Contact: ’)
addr = input(’Address: ’)
marks = list(map(float, input(’Marks (3 subjects) space-separated: ’).split()))
total = sum(marks)
avg = total / len(marks)
print(’---- Student Record ----’)
print(’Name:’, name)
print(’Roll:’, roll, ’Class:’, std)
print(’DOB:’, dob)
print(’Contact:’, contact)
print(’Address:’, addr)
print(’Total Marks:’, total)
print(’Average:’, avg)
19 Documentation Checklist
• State program objective at top as comment.
• Document function purpose and inputs/outputs.
• Insert comments for non-trivial logic. Avoid over-commenting trivial lines.
• Use descriptive variable names and consistent indentation (PEP8 recommended).
• Include sample input/output in comments where helpful.
20 Summary
This chapter covers the fundamentals for beginning programming in Python: basic syntax,
data types, operators, I/O, type conversion, debugging, and a rich set of examples and
exercises that form the foundation for later chapters.
11