Lesson 02

Loops and Lists

Repeating actions and working with collections

Recap

Lesson 1 — foundation

  • Variables and data types
  • print() and input()
  • Arithmetic and f-strings
  • Value comparison
  • Logical operators
  • if / elif / else

Today

Loops and Lists

while
for · range()
break · continue
creating lists
slices and methods
iterating collections

Motivation

Why we need loops

A program executes the same block of code multiple times, while a condition holds or until it iterates through an entire collection.

Without loops

One hundred lines

print("Hello") print("Hello") print("Hello") # ... × 100
With loops

Three lines

for i in range(100): print("Hello")

Topic 14

The while loop

Repeats a block of code while a condition is true

i = 1 while i <= 5: print(i) i = i + 1
1 2 3 4 5
Structure

Condition → block → back to condition. When the condition becomes false, the loop ends.

Step by step

How while works

Each iteration: check condition → execute block → return

i = 1 while i <= 5: print(i) i = i + 1
i i ≤ 5 print
1True1
2True2
3True3
4True4
5True5
6Falseexit

Example

Sum from 1 to 10

total = 0 i = 1 while i <= 10: total = total + i i = i + 1 print(total)
55

An accumulator variable collects the result while the condition holds.

Warning

Infinite loop

If the condition never becomes false, the program hangs

i = 1 while i <= 5: print(i) # forgot to increment i
If the program hangs

Interrupt execution with Ctrl + C in the terminal or the stop button in Jupyter.

Question

What does this code output?

x = 5 while x > 0: print(x) x = x - 1
A1 2 3 4 5
B5 4 3 2 1
C5 4 3 2 1 0
DInfinite loop

Take a minute to think →

Topic 15

The for loop

Repetition with a known number of iterations

for i in range(5): print(i)
0 1 2 3 4

The variable i takes values from the sequence one by one.

Step by step

How for works

range() yields values, the loop runs the body for each one

for i in range(1, 6): print(i * i)
Iteration i i × i
111
224
339
4416
5525

The loop ends automatically when the sequence is exhausted.

range()

How range() works

Creates a sequence of numbers

Call Sequence
range(5) 0, 1, 2, 3, 4
range(1, 6) 1, 2, 3, 4, 5
range(0, 10, 2) 0, 2, 4, 6, 8
range(10, 0, -1) 10, 9, 8, ..., 1
Note

The end value is not included in the range. range(5) produces numbers from 0 to 4.

Example

Sum using for

total = 0 for i in range(1, 11): total = total + i print(total)
55

Same result as the while-version, but shorter and without manual counter management.

Question

When to use for vs while?

Afor - when iteration count is known upfront
Bwhile - until some condition holds
COnly while - it is universal
DBoth A and B are correct

Take a minute to think →

Topic 16

break and continue

Flow control inside a loop

break

Exit the loop

Terminates the loop entirely. All remaining iterations are skipped.

continue

Next iteration

Skips the rest of the current iteration and moves to the next one.

break

Exit the loop

for i in range(10): if i == 5: break print(i)
0 1 2 3 4

When i reaches 5, the loop breaks. Numbers 5–9 are not printed.

continue

Skip iteration

for i in range(10): if i % 2 == 0: continue print(i)
1 3 5 7 9

Even numbers are skipped. The loop moves to the next iteration, bypassing print.

Topic 17

Lists

An ordered collection of elements

numbers = [1, 2, 3, 4, 5] fruits = ["apple", "pear", "plum"] mixed = [1, "two", 3.0, True] empty = []
Note

A list can contain elements of different types. Element order is preserved.

Access

Indexing

Indexing starts from zero

0"apple"-3
1"pear"-2
2"plum"-1
fruits = ["apple", "pear", "plum"] print(fruits[0]) # apple print(fruits[2]) # plum print(fruits[-1]) # plum (last) print(fruits[-2]) # pear (second to last)

Slicing

Slicing

list[start:end:step] — end is not included

nums = [10, 20, 30, 40, 50] nums[1:3] # [20, 30] nums[:2] # [10, 20] nums[3:] # [40, 50] nums[::2] # [10, 30, 50] nums[::-1] # [50, 40, 30, 20, 10]

Slicing returns a new list. The original is unchanged.

Topic 18

Common methods

Method Action
list.append(x) Add element to the end
list.remove(x) Remove first occurrence of x
list.pop() Remove and return last element
list.sort() Sort in place
list.reverse() Reverse in place
len(list) Length (this is a function)

Question

What does this code output?

nums = [1, 2, 3, 4, 5] print(nums[1:4])
A[1, 2, 3]
B[2, 3, 4]
C[2, 3, 4, 5]
D[1, 2, 3, 4]

Take a minute to think →

Topic 19

Iterating collections

for directly over a list, without indices

fruits = ["apple", "pear", "plum"] for fruit in fruits: print(fruit)
apple pear plum

The variable fruit takes the value of each list element in turn.

Bonus

Iterating a string

A string behaves like a sequence of characters

word = "Python" for letter in word: print(letter)
P y t h o n

Indexing and slicing work the same way for strings as for lists.

Exercise 1

Sum of even numbers

15:00
  1. 1 Ask the user for an integer N
  2. 2 Use for and range to iterate from 1 to N
  3. 3 Add only even numbers to the sum
  4. 4 Print the total

Hint: check evenness with i % 2 == 0.

Solution

Solution 1 walkthrough

n = int(input("Enter N: ")) total = 0 for i in range(1, n + 1): if i % 2 == 0: total = total + i print(f"Sum of evens from 1 to {n}: {total}")
read N for loop filter % accumulate print

Exercise 2

Analyzing grades

15:00
grades = [3, 5, 4, 2, 5, 4, 3, 5, 4, 5]
  1. 1 Count the number of excellent grades (5)
  2. 2 Compute the arithmetic mean
  3. 3 Print both values

Hint: sum(list) and len(list) simplify this.

Solution

Solution 2 walkthrough

grades = [3, 5, 4, 2, 5, 4, 3, 5, 4, 5] excellent = 0 for grade in grades: if grade == 5: excellent = excellent + 1 average = sum(grades) / len(grades) print(f"Excellent grades: {excellent}") print(f"Average: {average}")
list counter sum / len print

Practical exercises

Jupyter Notebook

10 tasks covering the lesson topics. Open in Jupyter or VS Code and work through them.

.ipynb
lesson2_tasks.ipynb
10 practical exercises
Download EN Скачать RU Yuklab olish UZ

Summary

Lesson summary

  • while loop and exit condition
  • for loop with range()
  • break and continue
  • Creating and indexing lists
  • Slicing and steps
  • List methods: append, remove, pop, sort
  • Iterating a list with for
  • Strings as sequences
Next lesson

Functions and dictionaries - organizing code and key-value data structures

Questions?

Telegram: @gokalqurt

Python · Lesson 2
RU UZ EN
1 / 31