L
LLLOS.ai
Learn
L
Class 9 Artificial Intelligence Chapter 0 of 4

Chapter 8 — Introduction to Python

Start learning → Step-by-step lesson with a teacher voice, questions and notes.

Reading view

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.

Topic 1 of 10
⌨️1

Programming and the Python language

By the end you canExplain what a program is and why Python is a good first language.

1Think first

How is a computer program like a recipe?No wrong answer. Think for a moment, then read on.

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?

FieldWhat Python does there
Artificial Intelligence and machine learningtraining models that recognise images, speech and text
Data sciencecleaning data, finding averages and trends, drawing charts
Web developmentrunning the server side of websites
Automationrepeating boring computer tasks such as renaming hundreds of files
Games and educationsimple 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.

Formulas to remember
  1. Program = an ordered list of instructions
  2. Interpreter: translates and runs one line at a time
Whena line has a mistakeThenthe interpreter stops at that line and shows an error
Whenyou want to test one small ideaThenuse interactive mode; for a full program use script mode

3Worked example

Write and run a program that shows the message Welcome to AI.
Step 1Open IDLE or an online Python compiler.
Step 2Type print("Welcome to AI") in a new file.
Step 3Save it as welcome.py and run it.
Step 4The screen shows: Welcome to AI
More examples
  • 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

One line to keepA program is a list of exact instructions; Python is a readable, interpreted language widely used in AI.
Common mistake. Typing Print with a capital P. Python is case-sensitive, so only print works.
Topic 2 of 10
🤖2

The print() function and comments

By the end you canUse print() to show text, numbers and patterns, and add comments.

1Think first

Why does print("15 + 20") show something different from print(15 + 20)?No wrong answer. Think for a moment, then read on.

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.

Formulas to remember
  1. print(item1, item2, ..., sep=" ", end="\n")
  2. Text in quotes is printed as it is; calculations without quotes are worked out
Whenitems are separated by commas inside print()Thenthey are printed with a space between them, unless sep is changed
Whena line begins with #ThenPython ignores it because it is a comment

3Worked example

Print the square of 7 with a message.
Step 1Write the message as a string and the calculation without quotes.
Step 2print("Square of 7 is", 7 * 7)
Step 3Python works out 7 * 7 = 49.
Step 4Output: Square of 7 is 49
More examples
  • 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

One line to keepprint() shows text in quotes exactly and works out anything without quotes; # starts a comment.
Common mistake. Mixing quotes, such as starting with " and ending with ', which causes a SyntaxError.
Topic 3 of 10
📊3

Variables and data types

By the end you canCreate variables with valid names and identify int, float, str and bool values.

1Think first

In what way is a variable like a labelled locker?No wrong answer. Think for a moment, then read on.

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:

TypeMeaningExamples
int (integer)whole numbers, positive, negative or zero14, -3, 0, 2026
floatnumbers with a decimal point1.52, 4.5, -0.25, 3.0
str (string)text, written in quotes"Isha", 'IX', "42"
bool (Boolean)a truth value used in decisionsTrue, 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.

Formulas to remember
  1. variable_name = value
  2. type(value) gives the data type
Whena value is assigned to an existing variableThenthe old value is replaced
Whena number is written in quotesThenit becomes a string, and + joins it instead of adding

3Worked example

Which names are valid: total_marks, 2nd_place, Class9, my name?
Step 1total_marks uses letters and _ and starts with a letter: valid.
Step 22nd_place starts with a digit: invalid.
Step 3Class9 starts with a letter: valid.
Step 4my name contains a space: invalid.
More examples
  • 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

One line to keepA variable is a name for a stored value; = assigns, and every value has a type such as int, float, str or bool.
Common mistake. Reading = as 'equals'. It means 'store the right side in the left side'.
Topic 4 of 10
👑4

Taking input and converting types

By the end you canRead values from the user with input() and convert them with int(), float() and str().

1Think first

If a user types 15 and 20, why might a program print 1520?No wrong answer. Think for a moment, then read on.

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.

FunctionWhat it doesExample and result
int(x)makes a whole numberint("25") gives 25; int(7.9) gives 7 (the decimal part is cut off, not rounded)
float(x)makes a decimal numberfloat("4.5") gives 4.5; float(3) gives 3.0
str(x)makes textstr(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.

Formulas to remember
  1. variable = input("prompt") gives a string
  2. number = int(input("prompt")) or float(input("prompt"))
Wheninput() reads a valueThenthe value is a string until it is converted
Whenan int and a float are combined in a calculationThenthe result is a float

3Worked example

Write a program that reads a length in kilometres and prints it in metres.
Step 1km = float(input("Length in km: "))
Step 2m = km * 1000
Step 3print(km, "km =", m, "m")
Step 4If the user types 2.5, the output is 2.5 km = 2500.0 m
More examples
  • 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

One line to keepinput() always returns text; convert it with int() or float() before doing arithmetic.
Common mistake. Forgetting int() or float() around input() and getting joined text instead of a sum.
Topic 5 of 10
🤖5

Arithmetic operators and expressions

By the end you canUse arithmetic operators and the order of operations to write correct expressions.

1Think first

Is 2 + 3 * 4 equal to 20 or to 14 in Python?No wrong answer. Think for a moment, then read on.

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.

OperatorNameExampleResult
+addition17 + 522
-subtraction17 - 512
*multiplication17 * 585
/division (always gives a float)17 / 53.4
//floor division (whole-number part)17 // 53
%modulus (remainder)17 % 52
**exponent (power)2 ** 38

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.

Formulas to remember
  1. Simple interest = principal * rate * time / 100
  2. Average = (a + b + c) / 3
  3. Precedence: () then ** then * / // % then + -
Whenyou divide with /Thenthe result is always a float
Whenan expression has no bracketsThen** is done first, then * / // %, then + and -

3Worked example

Find the area and perimeter of a rectangle of length 12 and breadth 7.5.
Step 1length = 12 and breadth = 7.5
Step 2area = length * breadth = 90.0
Step 3perimeter = 2 * (length + breadth) = 2 * 19.5 = 39.0
Step 4print("Area =", area, "Perimeter =", perimeter)
More examples
  • 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

One line to keepPython has seven arithmetic operators and follows the usual order of operations; use brackets to be safe.
Common mistake. Writing m1 + m2 + m3 / 3 for an average, which divides only m3 by 3.
Topic 6 of 10
🤖6

Comparison, logical and assignment operators

By the end you canWrite conditions with comparison and logical operators and update variables with assignment operators.

1Think first

What answer does a program get when it asks a question like 'Is age at least 18?'No wrong answer. Think for a moment, then read on.

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:

OperatorMeaningExample (age = 16)Result
==equal toage == 16True
!=not equal toage != 16False
>greater thanage > 18False
<less thanage < 18True
>=greater than or equal toage >= 18False
<=less than or equal toage <= 16True

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 formMeans the same as
x += 5x = x + 5
x -= 5x = x - 5
x *= 5x = x * 5
x /= 5x = x / 5
x //= 5x = x // 5
x %= 5x = 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.

Formulas to remember
  1. Comparison: == != > < >= <=
  2. Logical: and, or, not
  3. x += n means x = x + n
Whentwo conditions are joined with andThenthe result is True only if both are True
Whentwo conditions are joined with orThenthe result is True if either one is True

3Worked example

marks = 72. Find the value of marks >= 33 and marks >= 75.
Step 1marks >= 33 is True because 72 is at least 33.
Step 2marks >= 75 is False because 72 is below 75.
Step 3True and False gives False.
Step 4So the whole condition is False.
More examples
  • 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

One line to keepComparison and logical operators give True or False; += and similar operators update a variable in place.
Common mistake. Using = instead of == inside a condition, which is a SyntaxError in an if statement.
Topic 7 of 10
👑7

Making decisions: if, elif and else

By the end you canWrite if, if-else and if-elif-else statements with correct indentation and order of conditions.

1Think first

How can a program choose between two different actions?No wrong answer. Think for a moment, then read on.

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.

Formulas to remember
  1. if condition: block
  2. if condition: block else: block
  3. if c1: ... elif c2: ... else: ...
Whenseveral elif conditions are TrueThenonly the block of the first True condition runs
Whenno condition is TrueThenthe else block runs, if there is one

3Worked example

Write a program that prints Even or Odd for a number typed by the user.
Step 1n = int(input("Enter a number: "))
Step 2if n % 2 == 0: print("Even")
Step 3else: print("Odd")
Step 4For 14 the output is Even; for 9 it is Odd.
More examples
  • 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

One line to keepif, elif and else let a program choose; Python runs the first True branch and uses indentation to mark blocks.
Common mistake. Putting a weak condition first in an elif ladder, so stricter conditions below are never reached.
Topic 8 of 10
🤖8

Repeating steps: for and while loops

By the end you canUse for loops with range() and while loops with a start, condition and update.

1Think first

How could you print the numbers from 1 to 100 without writing 100 print statements?No wrong answer. Think for a moment, then read on.

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.

Formulas to remember
  1. range(stop), range(start, stop), range(start, stop, step): stop is not included
  2. Sum of first n natural numbers = n(n + 1)/2
Whenrange(1, 11) is usedThenthe loop runs for 1 to 10; 11 is not included
Whena while loop has no update stepThenits condition never becomes False and it loops for ever

3Worked example

Print the first 10 even numbers using a while loop.
Step 1Start with n = 2.
Step 2while n is at most 20: print(n), then n += 2.
Step 3The loop prints 2, 4, 6, ..., 20.
Step 4When n becomes 22 the condition is False and the loop stops.
More examples
  • 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

One line to keepfor repeats over a sequence such as range(); while repeats while a condition is True and needs an update.
Common mistake. Expecting range(1, 10) to include 10; the stop value is always left out.
Topic 9 of 10
🤖9

Lists: storing many values

By the end you canCreate a list, read items with positive and negative indexes and take slices.

1Think first

How can one variable hold the marks of a whole class?No wrong answer. Think for a moment, then read on.

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].

Item2312596544
Positive index012345
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.

Formulas to remember
  1. list[i]: item at index i (first index is 0)
  2. list[a:b]: items from index a to b - 1
  3. len(list): number of items
Whena list has n itemsThenthe positive indexes run from 0 to n - 1 and the negative ones from -n to -1
Whena slice list[a:b] is takenThenthe item at index b is not included

3Worked example

For colours = ["red", "green", "blue", "pink"], find colours[2], colours[-1] and colours[1:3].
Step 1Indexes are red 0, green 1, blue 2, pink 3.
Step 2colours[2] is "blue".
Step 3colours[-1] is the last item, "pink".
Step 4colours[1:3] takes indexes 1 and 2: ["green", "blue"].
More examples
  • 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

One line to keepA list keeps many values in order; indexes start at 0 from the left and at -1 from the right.
Common mistake. Thinking the first item is at index 1. In Python the first index is 0.
Topic 10 of 10
⚙️10

Working with lists: add, remove, sort and loop

By the end you canChange lists with append, extend, insert, remove, del and sort, and process them with loops.

1Think first

How would a program update the list of a quiz team when one student leaves and another joins?No wrong answer. Think for a moment, then read on.

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").

OperationWhat 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.

Formulas to remember
  1. L.append(x), L.extend(list), L.insert(i, x)
  2. L.remove(x), del L[i], L.pop()
  3. Average = sum(L) / len(L)
Whenappend is given a listThenthe whole list is added as one item; use extend to add its items separately
Whenan item is deletedThenall later items move one place to the left

3Worked example

L = [5, 3, 8]. Show L after L.append(1), L.sort() and L.pop().
Step 1L.append(1) gives [5, 3, 8, 1].
Step 2L.sort() gives [1, 3, 5, 8].
Step 3L.pop() removes the last item 8.
Step 4L is now [1, 3, 5].
More examples
  • 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

One line to keepList methods change a list in place; a for loop with a running total processes every item.
Common mistake. Using append when you meant extend, which puts a list inside the list.

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.

  1. 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 एक इंटरप्रेटर का उपयोग करता है जो प्रोग्राम को एक-एक पंक्ति अनुवाद करके चलाता है और त्रुटि वाली पहली पंक्ति पर रुक जाता है।

  2. 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 छपता है।

  3. 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() उसे संख्या में बदलता है ताकि उसका योग हो सके।

  4. 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 है।

  5. 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 में हाइफ़न है, इसलिए दोनों अमान्य हैं।

  6. 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 पर दूसरा संदेश दिखेगा।

  7. 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 देता है।

  8. 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 छपता है।

  9. 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 है।

  10. 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() दूसरी सूची के हर आइटम को अलग-अलग अंत में जोड़ता है।

  11. 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 all

Foundational 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.

Loading related laws…
Sourced from 0 content files · LLOS Learn · browse all chapters