Overview
This chapter is a first course in Python, the programming language most used for Artificial Intelligence and data work, and it follows Unit 5 of the CBSE Class 9 AI syllabus. You begin with what a program is, how the Python interpreter runs it line by line, and the difference between interactive and script mode. You then learn the print() function and comments, variables and their naming rules, and the basic data types: integers, floats, strings and Boolean values. You read values from the user with input() and convert them with int(), float() and str(), and you write expressions with arithmetic, comparison, logical and assignment operators, following the order of operations. Next comes flow of control: decisions with if, elif and else, and repetition with for loops using range() and with while loops. Finally you store many values in a list, read them with positive and negative indexes and slices, and change them with append, extend, remove, del and sort. Every program in the chapter comes from or follows the CBSE practical list and is shown with the output it really produces, so you can type it, run it and check.
हिंदी में पढ़ें
अपने पहले Python प्रोग्राम लिखें: print और input, वेरिएबल, ऑपरेटर, निर्णय, लूप और सूचियाँ, हर उदाहरण जाँचा हुआ।
Learning Objectives
- Explain what a program is and how Python's interpreter runs it
- Use print() with text, numbers, sep and end, and write comments
- Create variables with valid names and identify int, float, str and bool values
- Read user input and convert it with int(), float() and str()
- Write expressions with arithmetic operators and the correct order of operations
- Use comparison, logical and assignment operators
- Write if, if-else and if-elif-else statements with correct indentation
- Use for loops with range() and while loops to repeat steps
- Create, index, slice and modify lists and process them with loops
Topics in this chapter
10 topics · tap a topic title to jump straight to it.
Programming and the Python language
1Think first
2The idea, in plain words
Think of a recipe. It is a list of exact steps, written in an order, that anyone can follow to get the same dish. A computer program is the same idea: a list of exact instructions that a computer follows, one after another. Writing those instructions is called programming or coding, and the language you write them in is a programming language.
Why do we need a special language? A computer understands only machine code, long strings of 0s and 1s. People cannot write large programs in 0s and 1s, so we use a high-level language that looks a little like English. A translator program then converts it for the machine. Python uses a translator called an interpreter: it reads your program line by line and runs each line straight away. If a line has a mistake, Python stops there and shows an error message, which makes mistakes easy to find.
Why Python? Python was created by Guido van Rossum and first released in 1991. It is popular in schools and in industry because:
- its rules (syntax) are short and readable, so beginners spend time on ideas rather than on symbols;
- it is free and open source, and it runs on Windows, macOS, Linux and even in a web browser;
- it has thousands of ready-made libraries, including the main tools used for AI and data work;
- the same language is used by beginners and by large companies.
Where is Python used?
| Field | What Python does there |
| Artificial Intelligence and machine learning | training models that recognise images, speech and text |
| Data science | cleaning data, finding averages and trends, drawing charts |
| Web development | running the server side of websites |
| Automation | repeating boring computer tasks such as renaming hundreds of files |
| Games and education | simple games and learning platforms |
Where do you write Python? You can install Python with its editor IDLE, use a distribution such as Anaconda with Jupyter Notebook, or use any online Python compiler in a browser. Python has two ways of working. In interactive mode you type one statement at the >>> prompt and see the result at once, which is good for testing small ideas. In script mode you write a whole program in a file ending in .py, save it and run it, which is how real programs are written. The CBSE course also suggests starting with game-based platforms such as Code Combat, where you guide a character by typing real Python commands.
Your first program. The classic first program prints a greeting:
Code
print("Hello, World!")
Output
Hello, World!
The word print is a built-in function: a named piece of code that does a job. The text inside the quotes is shown on the screen exactly as written. In the rest of this chapter, every program is shown together with the output it really produces, so you can type it in and check.
- Program = an ordered list of instructions
- Interpreter: translates and runs one line at a time
3Worked example
- A recipe is like a program: exact steps in a fixed order.
- Python reads a program line by line and stops at the first error.
- Interactive mode: type 2 + 3 at the prompt and see 5 at once.
- Script mode: save a file as marks.py and run it.
4Your turn
What does the Python interpreter do?
5Remember this
The print() function and comments
1Think first
2The idea, in plain words
Every program needs a way to show its results. In Python this is the print() function. Whatever you put inside the brackets is shown on the screen, and then the cursor moves to a new line.
Printing text. Text in a program is called a string and is written inside quotes. Single quotes and double quotes both work, but they must match. If the text itself contains an apostrophe, such as Father's, use double quotes outside. The CBSE practical list starts with a program that prints personal details:
Code
print("Name: Ananya Sharma")
print("Father's Name: Rakesh Sharma")
print("Class: IX")
print("School: Kendriya Vidyalaya")
Output
Name: Ananya Sharma
Father's Name: Rakesh Sharma
Class: IX
School: Kendriya Vidyalaya
Printing patterns. Several print statements, one under another, can draw a simple pattern:
Code
print("*")
print("**")
print("***")
print("****")
Output
*
**
***
****
Printing several items. You can give print() several items separated by commas. Python prints them with one space between them. Numbers and calculations need no quotes: 15 + 20 is worked out first and the answer is printed. Two optional settings change the layout: sep sets what goes between items, and end sets what is printed at the end instead of a new line.
Code
print("Sum of", 15, "and", 20, "is", 15 + 20)
print("A", "B", "C", sep="-")
print("Same", end=" ")
print("line")
Output
Sum of 15 and 20 is 35
A-B-C
Same line
Comments. A line that starts with # is a comment. Python ignores it completely; it is a note for people who read the code. Good comments explain why something is done. For example, # convert km to m before printing. Comments can also sit at the end of a line of code.
Text or number? Compare print("15 + 20") and print(15 + 20). The first shows the characters 15 + 20 exactly, because they are inside quotes. The second shows 35, because Python calculates it. Quotes decide whether Python treats something as plain text or as a value to work out.
Common errors. Forgetting a closing quote or bracket gives a SyntaxError. Writing a word without quotes, like print(Hello), makes Python look for a variable called Hello, and you get a NameError. Read the error message: it names the line where Python got stuck.
- print(item1, item2, ..., sep=" ", end="\n")
- Text in quotes is printed as it is; calculations without quotes are worked out
3Worked example
- print("Class: IX") shows Class: IX
- print(7 * 7) shows 49
- print("A", "B", sep="-") shows A-B
- # This is a comment and is not run
4Your turn
What is the output of print("5" , 5 + 5)?
5Remember this
Variables and data types
1Think first
2The idea, in plain words
A school locker has a label on the door and something stored inside. You can open it, look at the contents and replace them. A variable in Python works the same way: it is a name that refers to a value stored in the computer's memory.
Creating a variable. You create a variable by assignment, using the = sign: the name goes on the left and the value on the right. In Python, = does not mean 'is equal to' as in mathematics. It means 'store the value on the right under the name on the left'. You can change the value later, and the old value is replaced.
Code
name = "Isha"
age = 14
height = 1.52
print(name, age, height)
print(type(name), type(age), type(height))
age = age + 1
print("Next year", name, "will be", age)
Output
Isha 14 1.52
<class 'str'> <class 'int'> <class 'float'>
Next year Isha will be 15
Notice the line age = age + 1. Python first works out the right side using the old value (14 + 1 = 15), then stores 15 back in age. In mathematics this line would make no sense, but in programming it is very common.
Rules for variable names.
- A name can contain letters, digits and the underscore _ only.
- It must start with a letter or an underscore, never a digit: marks1 is valid, 1marks is not.
- No spaces are allowed: use total_marks, not total marks.
- Names are case-sensitive: Age and age are two different variables.
- A keyword (a word Python reserves, such as if, for, while, True, False or None) cannot be used as a name.
Choose meaningful names. principal_amount tells the reader much more than p.
Data types. Every value has a type, which decides what you can do with it. The CBSE course uses these basic types:
| Type | Meaning | Examples |
| int (integer) | whole numbers, positive, negative or zero | 14, -3, 0, 2026 |
| float | numbers with a decimal point | 1.52, 4.5, -0.25, 3.0 |
| str (string) | text, written in quotes | "Isha", 'IX', "42" |
| bool (Boolean) | a truth value used in decisions | True, False |
The built-in function type() tells you the type of any value, as the output above shows. Be careful: "42" in quotes is a string, not a number, so "42" + "8" joins the text to give "428" while 42 + 8 gives 50.
Python decides the type for you. You never write the type when you create a variable; Python looks at the value. A variable can even hold a different type later. This is called dynamic typing. It is convenient, but it also means you must keep track of what each variable holds.
- variable_name = value
- type(value) gives the data type
3Worked example
- marks = 87 stores the integer 87
- rate_of_interest = 4.5 stores a float
- school = "DPS" stores a string
- type(3.0) is float, type(3) is int
4Your turn
What is the type of the value "3.5"?
5Remember this
Taking input and converting types
1Think first
2The idea, in plain words
A calculator that can add only 15 and 20 is not much use. Real programs ask the user for values. In Python, the input() function shows a message (the prompt), waits for the user to type something and press Enter, and gives back what was typed.
Code
name = input("Enter your name: ")
print("Hello", name)
Output (the values after each prompt were typed by the user)
Enter your name: Kartik
Hello Kartik
input() always gives a string. This is the most important fact about input(). Even if the user types 25, the program receives the text "25". Watch what happens when we try to add two numbers this way:
Code
a = input("First number: ")
b = input("Second number: ")
print(a + b)
Output (the values after each prompt were typed by the user)
First number: 15
Second number: 20
1520
The output is 1520, not 35, because + joins two strings. The fix is type conversion: wrap input() in int() or float() to turn the text into a number.
Code
a = int(input("First number: "))
b = int(input("Second number: "))
print("Sum =", a + b)
Output (the values after each prompt were typed by the user)
First number: 15
Second number: 20
Sum = 35
Conversion functions.
| Function | What it does | Example and result |
| int(x) | makes a whole number | int("25") gives 25; int(7.9) gives 7 (the decimal part is cut off, not rounded) |
| float(x) | makes a decimal number | float("4.5") gives 4.5; float(3) gives 3.0 |
| str(x) | makes text | str(10) gives "10" |
Code
print(int("25") + 5)
print(float("4.5") * 2)
print(str(10) + "0")
print(int(7.9))
Output
30
9.0
100
7
Use int() when the value must be whole (number of students, age in years) and float() when decimals are possible (price, height, rate of interest). If the user types something that is not a number, such as ten, int() cannot convert it and Python stops with a ValueError. Changing a type with a function in this way is called explicit conversion. Python also converts on its own in some cases: 2 + 1.5 gives 3.5, a float, because an int mixed with a float becomes a float. That is implicit conversion.
Good prompts. A prompt should tell the user exactly what to type, including units: Enter length in km: is better than Enter: . End the prompt with a colon and a space so the typed value does not stick to the message.
- variable = input("prompt") gives a string
- number = int(input("prompt")) or float(input("prompt"))
3Worked example
- age = int(input("Age: ")) stores a whole number
- price = float(input("Price: ")) allows decimals
- input() returns "20" as text even if 20 is typed
- int("abc") causes a ValueError
4Your turn
x = input() and the user types 8. What is x * 2?
5Remember this
Arithmetic operators and expressions
1Think first
2The idea, in plain words
A shopkeeper adds up bills, a teacher works out averages and a bank calculates interest. Python can do all of these with arithmetic operators. An expression is any combination of values, variables and operators that Python can work out to a single value, such as principal * rate * time / 100.
| Operator | Name | Example | Result |
| + | addition | 17 + 5 | 22 |
| - | subtraction | 17 - 5 | 12 |
| * | multiplication | 17 * 5 | 85 |
| / | division (always gives a float) | 17 / 5 | 3.4 |
| // | floor division (whole-number part) | 17 // 5 | 3 |
| % | modulus (remainder) | 17 % 5 | 2 |
| ** | exponent (power) | 2 ** 3 | 8 |
Code
a = 17
b = 5
print(a + b, a - b, a * b)
print(a / b, a // b, a % b)
print(2 ** 3)
Output
22 12 85
3.4 3 2
8
Useful facts. Division with / always gives a float, even 10 / 2 gives 5.0. Floor division // and modulus % go together: 17 = 5 × 3 + 2, so 17 // 5 is 3 and 17 % 5 is 2. The remainder is very handy: n % 2 is 0 for even numbers and 1 for odd numbers.
Order of operations (precedence). Python follows the same order you know from mathematics. Brackets come first, then powers (**), then *, /, // and %, and finally + and -. Operators of the same level are worked out from left to right (powers are the exception: they go right to left).
Code
print(2 + 3 * 4)
print((2 + 3) * 4)
print(20 - 6 / 2 ** 2)
Output
14
20
18.5
In the last line, 2 ** 2 = 4 is done first, then 6 / 4 = 1.5, then 20 - 1.5 = 18.5. When in doubt, add brackets: they make your intention clear to the reader as well as to Python.
A CBSE practical: simple interest. Simple interest = principal × rate × time ÷ 100. With principal 2000, rate 4.5 per cent and time 10 years:
Code
principal_amount = 2000
rate_of_interest = 4.5
time = 10
si = principal_amount * rate_of_interest * time / 100
print("Simple Interest =", si)
Output
Simple Interest = 900.0
Check: 2000 × 4.5 = 9000, 9000 × 10 = 90000, 90000 ÷ 100 = 900. The answer is a float (900.0) because 4.5 is a float and because / always gives a float.
More expressions from the practical list. The area of a rectangle is length * breadth and its perimeter is 2 * (length + breadth). The area of a triangle is 0.5 * base * height. The average of three marks is (m1 + m2 + m3) / 3; without the brackets only m3 would be divided by 3, which is a classic mistake.
- Simple interest = principal * rate * time / 100
- Average = (a + b + c) / 3
- Precedence: () then ** then * / // % then + -
3Worked example
- 17 // 5 = 3 and 17 % 5 = 2
- 10 / 2 = 5.0 (a float)
- 2 ** 10 = 1024
- (m1 + m2 + m3) / 3 is the average of three marks
4Your turn
What is the value of 23 % 4?
5Remember this
Comparison, logical and assignment operators
1Think first
2The idea, in plain words
Before you cross a road you ask yourself questions: Is the light green? Is a car coming? Programs ask questions too, and the answer to each question is either True or False. Such values are called Boolean values, and the operators that produce them are the comparison and logical operators.
Comparison (relational) operators compare two values:
| Operator | Meaning | Example (age = 16) | Result |
| == | equal to | age == 16 | True |
| != | not equal to | age != 16 | False |
| > | greater than | age > 18 | False |
| < | less than | age < 18 | True |
| >= | greater than or equal to | age >= 18 | False |
| <= | less than or equal to | age <= 16 | True |
Do not confuse = with ==. A single = stores a value; a double == asks whether two values are equal.
Logical operators join or reverse conditions:
- and is True only if both conditions are True. A teenager is someone with age > 12 and age < 20.
- or is True if at least one condition is True. A ticket is free if age < 5 or age > 75.
- not reverses a condition: not True is False.
Code
age = 16
print(age >= 18)
print(age == 16, age != 16)
print(age > 13 and age < 20)
print(age < 13 or age > 60)
print(not age >= 18)
Output
False
True False
True
False
True
Assignment operators. Programs often update a variable using its own value, as in score = score + 5. Python has short forms for this:
| Short form | Means the same as |
| x += 5 | x = x + 5 |
| x -= 5 | x = x - 5 |
| x *= 5 | x = x * 5 |
| x /= 5 | x = x / 5 |
| x //= 5 | x = x // 5 |
| x %= 5 | x = x % 5 |
Code
score = 10
score += 5
print(score)
score *= 2
print(score)
score -= 4
print(score)
score //= 3
print(score)
Output
15
30
26
8
Trace it: 10 + 5 = 15, then 15 × 2 = 30, then 30 - 4 = 26, then 26 // 3 = 8. The short forms will be used again and again in loops, for example to add up a running total with total += n.
Why this matters for AI. Even large AI systems end in simple decisions written with these operators. A spam filter may say: if the spam score is greater than or equal to 0.9, move the mail to the spam folder. A self-driving car checks whether distance < safe distance and speed > 0 before braking. The next topic shows how a program acts on such True or False answers.
- Comparison: == != > < >= <=
- Logical: and, or, not
- x += n means x = x + n
3Worked example
- 5 == 5 is True; 5 != 5 is False
- (7 > 3) and (2 > 9) is False
- (7 > 3) or (2 > 9) is True
- total += marks adds marks to total
4Your turn
x = 7. What is x % 2 == 1 or x > 10?
5Remember this
Making decisions: if, elif and else
1Think first
2The idea, in plain words
Every day you make decisions: if it is raining, take an umbrella, otherwise wear a cap. Programs make decisions the same way. Normally Python runs statements one after another from top to bottom; this is sequential flow. A conditional statement lets the program choose which statements to run, depending on whether a condition is True or False. This is called flow of control.
The if statement. It has a condition followed by a colon, and an indented block of statements underneath. The block runs only if the condition is True. Indentation (normally 4 spaces) is how Python knows which statements belong to the if; it is a rule, not a matter of style.
if ... else. The else block runs when the condition is False, so exactly one of the two blocks always runs. A CBSE practical: can a person vote?
Code
age = int(input("Enter your age: "))
if age >= 18:
print("You can vote.")
else:
print("You cannot vote yet.")
Output (the values after each prompt were typed by the user)
Enter your age: 16
You cannot vote yet.
if ... elif ... else. When there are more than two possibilities, add elif (short for 'else if'). Python checks the conditions from top to bottom and runs the block of the first condition that is True; it skips the rest. The else block, if present, runs only when no condition was True.
Code
n = int(input("Enter a number: "))
if n > 0:
print(n, "is positive")
elif n < 0:
print(n, "is negative")
else:
print("The number is zero")
Output (the values after each prompt were typed by the user)
Enter a number: -7
-7 is negative
Grades. The order of the conditions matters in a ladder like this one:
Code
marks = float(input("Enter marks out of 100: "))
if marks >= 90:
grade = "A"
elif marks >= 75:
grade = "B"
elif marks >= 60:
grade = "C"
elif marks >= 33:
grade = "D"
else:
grade = "E (needs improvement)"
print("Grade:", grade)
Output (the values after each prompt were typed by the user)
Enter marks out of 100: 82
Grade: B
For 82 marks, the first test (82 >= 90) is False, the second (82 >= 75) is True, so the grade is B and Python skips all the remaining tests. We do not need to write marks >= 75 and marks < 90, because a mark of 90 or more would already have been caught by the first test. If the tests were written in the opposite order, starting with marks >= 33, every pass mark would get a D. Always check the strictest condition first.
Flowchart. A decision is drawn as a diamond with two exits, Yes and No. The figure shows the voting program as a flowchart. Drawing the flowchart first helps you plan the conditions before writing code.
Typical errors. Forgetting the colon after the condition, forgetting to indent, or mixing tabs and spaces gives an error. Writing a condition such as if age >= "18" compares a number with text and fails, so convert inputs with int() first.
- if condition: block
- if condition: block else: block
- if c1: ... elif c2: ... else: ...
3Worked example
- if temperature > 38: print("Fever")
- if n % 2 == 0: even, else: odd
- Ticket price: elif ladders for child, adult and senior
- Spam filter: if score >= 0.9 move to spam
4Your turn
x = 5. if x > 3: print("A") elif x > 1: print("B") else: print("C"). What is printed?
5Remember this
Repeating steps: for and while loops
1Think first
2The idea, in plain words
Suppose you must print the numbers 1 to 100. Writing 100 print statements would be silly. A loop repeats a block of statements for you. Repetition is also called iteration, and each pass through the loop is one iteration. Python has two loops: for and while.
The for loop repeats once for each value in a sequence. The range() function produces a sequence of whole numbers:
Code
print(list(range(5)))
print(list(range(1, 6)))
print(list(range(2, 21, 2)))
Output
[0, 1, 2, 3, 4]
[1, 2, 3, 4, 5]
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
range(5) starts at 0 and stops before 5. range(1, 6) gives 1 to 5. A third number is the step: range(2, 21, 2) gives the first 10 even numbers. The stop value is never included, which is the most common source of 'off by one' mistakes.
First 10 natural numbers (a CBSE practical):
Code
for i in range(1, 11):
print(i, end=" ")
Output
1 2 3 4 5 6 7 8 9 10
Running total. To add numbers, start a variable at 0 and add each value inside the loop. The trace table shows how total grows: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55.
Code
total = 0
for n in range(1, 11):
total += n
print("Sum of first 10 natural numbers =", total)
Output
Sum of first 10 natural numbers = 55
The answer 55 agrees with the formula n(n + 1)/2 = 10 × 11 / 2 = 55. The table of 5 up to five terms is another short loop:
Code
for k in range(1, 6):
print("5 x", k, "=", 5 * k)
Output
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
The while loop repeats as long as its condition is True. It is useful when you do not know in advance how many times to repeat. It has three parts: a starting value set before the loop, a condition checked before each iteration, and an update inside the loop that moves towards making the condition False.
Code
n = int(input("Print odd numbers up to: "))
i = 1
while i <= n:
print(i, end=" ")
i += 2
Output (the values after each prompt were typed by the user)
Print odd numbers up to: 9
1 3 5 7 9
If you forget the update i += 2, i stays 1 for ever, the condition is always True, and the program never stops. This is an infinite loop; stop it with Ctrl + C.
for or while? Use for when you know how many times, or when you go through a sequence such as a list. Use while when you repeat until something happens, such as 'keep asking for a password until it is correct'. Loops are at the heart of AI too: a model is trained by repeating the same learning step thousands of times over the data.
- range(stop), range(start, stop), range(start, stop, step): stop is not included
- Sum of first n natural numbers = n(n + 1)/2
3Worked example
- for i in range(3): print("Hi") prints Hi three times
- range(2, 21, 2) gives 2, 4, ..., 20
- total += n inside a loop adds up numbers
- while password is wrong: ask again
4Your turn
How many numbers does for i in range(3, 9) produce?
5Remember this
Lists: storing many values
1Think first
2The idea, in plain words
A class register holds many names under one heading, in a fixed order, and each name has a roll number. A Python list is the same idea: one variable that holds many values in order. A list is written inside square brackets, with items separated by commas, for example marks = [78, 91, 66] or names = ["Arjun", "Isha"]. A list may even mix types, such as ["Riya", 14, 1.52].
Indexing. Each item has a position number called its index. Python counts from 0, so the first item is at index 0, the second at index 1, and so on. Python also allows negative indexing: -1 is the last item, -2 the second last. The figure shows both numberings for the CBSE practical list num = [23, 12, 5, 9, 65, 44].
| Item | 23 | 12 | 5 | 9 | 65 | 44 |
| Positive index | 0 | 1 | 2 | 3 | 4 | 5 |
| Negative index | -6 | -5 | -4 | -3 | -2 | -1 |
Slicing. num[a:b] gives a new list of the items from index a up to, but not including, index b. So num[1:4] gives the items at indexes 1, 2 and 3: the second to the fourth item. With negative indexes, num[-4:-1] gives the items at -4, -3 and -2: the third to the fifth item. The rule 'stop is not included' is the same as for range().
Code
num = [23, 12, 5, 9, 65, 44]
print(num)
print("Length:", len(num))
print(num[0], num[5], num[-1], num[-2])
print("Second to fourth:", num[1:4])
print("Third to fifth:", num[-4:-1])
Output
[23, 12, 5, 9, 65, 44]
Length: 6
23 44 44 65
Second to fourth: [12, 5, 9]
Third to fifth: [5, 9, 65]
len() gives the number of items. For a list of 6 items the valid indexes are 0 to 5 (or -6 to -1); asking for num[6] gives an IndexError because there is no seventh item.
Lists can be changed. Unlike a string, a list is mutable: you can replace an item by assigning to its index. num[0] = 30 changes the first item from 23 to 30. The next topic shows how to add, remove and sort items.
Why lists matter in AI. Data is almost always a collection: the marks of 40 students, the temperatures of 30 days, the pixel values of an image. Lists let a program keep such data together and process it with a loop. Later, in data science, you will meet more powerful structures (arrays and tables) that grow out of the same idea.
- list[i]: item at index i (first index is 0)
- list[a:b]: items from index a to b - 1
- len(list): number of items
3Worked example
- marks = [78, 91, 66]; marks[0] is 78
- marks[-1] is the last item, 66
- marks[0:2] is [78, 91]
- len([4, 8, 15, 16]) is 4
4Your turn
a = [10, 20, 30, 40, 50]. What is a[-2]?
5Remember this
Working with lists: add, remove, sort and loop
1Think first
2The idea, in plain words
Lists in real programs keep changing: students join a quiz team, some drop out, results are sorted. Python gives every list a set of methods, functions that are attached to the list and called with a dot, as in quiz.append("Jay").
| Operation | What it does |
| L.append(x) | adds x at the end |
| L.insert(i, x) | puts x at index i, shifting later items right |
| L.extend([a, b]) | adds all items of another list at the end |
| L.remove(x) | removes the first item equal to x |
| del L[i] | deletes the item at index i |
| L.pop() | removes and gives back the last item |
| L.sort() | arranges the items in ascending order |
| len(L), sum(L), max(L), min(L) | count, total, largest and smallest item |
CBSE practical: the science quiz team. Create the list, print it, delete Vikram, add Jay at the end, then remove the item at the second position (index 1):
Code
quiz = ["Arjun", "Sonakshi", "Vikram", "Sandhya", "Sonal", "Isha", "Kartik"]
print(quiz)
quiz.remove("Vikram")
print(quiz)
quiz.append("Jay")
print(quiz)
del quiz[1]
print(quiz)
Output
['Arjun', 'Sonakshi', 'Vikram', 'Sandhya', 'Sonal', 'Isha', 'Kartik']
['Arjun', 'Sonakshi', 'Sandhya', 'Sonal', 'Isha', 'Kartik']
['Arjun', 'Sonakshi', 'Sandhya', 'Sonal', 'Isha', 'Kartik', 'Jay']
['Arjun', 'Sandhya', 'Sonal', 'Isha', 'Kartik', 'Jay']
Follow each step. After removing Vikram the list has six names. Jay goes to the end. The second position is index 1, which now holds Sonakshi, so she is removed.
extend and sort. Add [14, 15, 12] to [10, 20, 30, 40] and sort the result:
Code
List_1 = [10, 20, 30, 40]
List_1.extend([14, 15, 12])
print(List_1)
List_1.sort()
print(List_1)
Output
[10, 20, 30, 40, 14, 15, 12]
[10, 12, 14, 15, 20, 30, 40]
Note the difference: append adds its argument as one item, while extend adds each item separately. List_1.append([14, 15, 12]) would put a whole list inside the list as a single item.
Changing every item with a loop. Create the first 10 even numbers and add 1 to each item:
Code
even = list(range(2, 21, 2))
print(even)
for i in range(len(even)):
even[i] = even[i] + 1
print(even)
Output
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
[3, 5, 7, 9, 11, 13, 15, 17, 19, 21]
Going through a list. A for loop can visit each item directly: for m in marks. This is the standard way to add up the numbers in a list (another CBSE practical). Python also has the ready-made functions sum(), max() and min(), which give the same total and confirm your loop is right:
Code
marks = [78, 91, 66, 85, 70]
total = 0
for m in marks:
total += m
print("Total =", total)
print("Average =", total / len(marks))
print("Check with sum():", sum(marks), max(marks), min(marks))
Output
Total = 390
Average = 78.0
Check with sum(): 390 91 66
Check by hand: 78 + 91 + 66 + 85 + 70 = 390 and 390 ÷ 5 = 78.0. Exactly this pattern of 'loop over the data, keep a running total, divide by the count' is how statistics such as the mean are computed in data science and AI.
- L.append(x), L.extend(list), L.insert(i, x)
- L.remove(x), del L[i], L.pop()
- Average = sum(L) / len(L)
3Worked example
- names.append("Jay") adds Jay at the end
- names.remove("Vikram") deletes Vikram
- del names[1] deletes the second item
- nums.sort() puts numbers in ascending order
4Your turn
L = [4, 7, 9]. After L.insert(1, 5), what is L?
5Remember this
Key Concepts
- Program
- An ordered set of instructions that a computer follows to do a task.
- Interpreter
- A translator that reads and runs a program one line at a time and stops at the first error, as Python does.
- Interactive and script mode
- Interactive mode runs one statement at the >>> prompt; script mode runs a whole program saved in a .py file.
- print()
- A built-in function that shows values on the screen; sep and end change the layout.
- Comment
- A note in the code starting with #; Python ignores it.
- Variable
- A name that refers to a value stored in memory, created with the assignment operator =.
- Data type
- The kind of value: int (whole number), float (decimal), str (text) or bool (True or False).
- input()
- A built-in function that shows a prompt and returns what the user types, always as a string.
- Type conversion
- Changing a value from one type to another with int(), float() or str().
- Arithmetic operators
- +, -, *, / (division), // (floor division), % (remainder) and ** (power).
- Operator precedence
- The order in which Python works out an expression: brackets, powers, then * / // %, then + and -.
- Comparison operators
- ==, !=, >, <, >= and <=; they compare two values and give True or False.
- Logical operators
- and, or and not; they join or reverse conditions.
- Assignment operators
- Short forms such as += and -= that update a variable using its own value.
- Conditional statement
- if, elif and else, which run a block only when a condition is True.
- Indentation
- The spaces at the start of a line that show which statements belong to a block.
- Loop
- A statement that repeats a block: for repeats over a sequence, while repeats as long as a condition is True.
- range()
- Produces a sequence of whole numbers from start up to, but not including, stop, with an optional step.
- List
- An ordered, changeable collection of values written in square brackets, indexed from 0.
- Slicing
- Taking part of a list with list[a:b], which gives items from index a up to b - 1.
End-of-Chapter Trial Paper & Test Questions
Topic-wise questions to test your understanding of every concept in this chapter.
-
Why is Python called an interpreted language? / Python को इंटरप्रेटेड भाषा क्यों कहा जाता है?
Show answer
Python uses an interpreter that translates and runs the program one line at a time, stopping at the first line with an error. / Python एक इंटरप्रेटर का उपयोग करता है जो प्रोग्राम को एक-एक पंक्ति अनुवाद करके चलाता है और त्रुटि वाली पहली पंक्ति पर रुक जाता है।
-
Write a program to find the sum of 15 and 20 and the square of 7. / 15 और 20 का योग तथा 7 का वर्ग ज्ञात करने का प्रोग्राम लिखिए।
Show answer
print("Sum =", 15 + 20) prints Sum = 35, and print("Square =", 7 ** 2) prints Square = 49. / print("Sum =", 15 + 20) से Sum = 35 छपता है और print("Square =", 7 ** 2) से Square = 49 छपता है।
-
Why does input() need int() or float() before doing arithmetic? / अंकगणित करने से पहले input() के साथ int() या float() क्यों आवश्यक है?
Show answer
input() always returns a string, so + would join the text; int() or float() converts it into a number so that it can be added. / input() हमेशा स्ट्रिंग देता है, इसलिए + पाठ को जोड़ देगा; int() या float() उसे संख्या में बदलता है ताकि उसका योग हो सके।
-
Find the output of print(17 // 5, 17 % 5, 2 ** 4). / print(17 // 5, 17 % 5, 2 ** 4) का आउटपुट ज्ञात कीजिए।
Show answer
The output is 3 2 16, because 17 divided by 5 gives quotient 3 and remainder 2, and 2 to the power 4 is 16. / आउटपुट 3 2 16 है, क्योंकि 17 को 5 से भाग देने पर भागफल 3 और शेषफल 2 आता है, तथा 2 की घात 4 का मान 16 है।
-
Which of these are valid variable names: total_marks, 9class, Name, my-age? / इनमें से कौन-से वैध वेरिएबल नाम हैं: total_marks, 9class, Name, my-age?
Show answer
total_marks and Name are valid; 9class starts with a digit and my-age contains a hyphen, so both are invalid. / total_marks और Name वैध हैं; 9class अंक से शुरू होता है और my-age में हाइफ़न है, इसलिए दोनों अमान्य हैं।
-
Write a program to check whether a person can vote. / जाँचने का प्रोग्राम लिखिए कि कोई व्यक्ति मतदान कर सकता है या नहीं।
Show answer
Read age = int(input("Age: ")); if age >= 18 print "You can vote." else print "You cannot vote yet." For age 16 the second message is shown. / age = int(input("Age: ")) पढ़ें; यदि age >= 18 है तो "You can vote." अन्यथा "You cannot vote yet." छापें। आयु 16 पर दूसरा संदेश दिखेगा।
-
What is the difference between = and ==? / = और == में क्या अंतर है?
Show answer
A single = assigns a value to a variable, while == compares two values and gives True or False. / एक = वेरिएबल में मान संग्रहीत करता है, जबकि == दो मानों की तुलना करके True या False देता है।
-
Write a loop to print the sum of the first 10 natural numbers. / प्रथम 10 प्राकृत संख्याओं का योग छापने के लिए लूप लिखिए।
Show answer
Set total = 0, then for n in range(1, 11): total += n, and finally print(total), which prints 55. / total = 0 रखें, फिर for n in range(1, 11): total += n, और अंत में print(total), जिससे 55 छपता है।
-
For num = [23, 12, 5, 9, 65, 44], what are len(num), num[1:4] and num[-1]? / num = [23, 12, 5, 9, 65, 44] के लिए len(num), num[1:4] और num[-1] क्या हैं?
Show answer
len(num) is 6, num[1:4] is [12, 5, 9] because index 4 is not included, and num[-1] is the last item 44. / len(num) 6 है, num[1:4] का मान [12, 5, 9] है क्योंकि सूचकांक 4 शामिल नहीं होता, और num[-1] अंतिम आइटम 44 है।
-
What is the difference between append() and extend()? / append() और extend() में क्या अंतर है?
Show answer
append() adds its argument as one item at the end, while extend() adds each item of another list separately at the end. / append() अपने तर्क को अंत में एक ही आइटम के रूप में जोड़ता है, जबकि extend() दूसरी सूची के हर आइटम को अलग-अलग अंत में जोड़ता है।
-
When is a while loop better than a for loop? Give an example. / for लूप की तुलना में while लूप कब बेहतर है? उदाहरण दीजिए।
Show answer
A while loop is better when the number of repetitions is not known in advance, for example asking for a password again and again until the correct one is typed. / जब दोहराव की संख्या पहले से ज्ञात न हो तब while लूप बेहतर है, जैसे सही पासवर्ड डाले जाने तक बार-बार पासवर्ड माँगना।
Related Laws & Principles
Explore allFoundational laws & principles behind this chapter. Each one opens a full page — what it says, why it matters, five practice questions and the mistakes to avoid.