Skip to main content
EDU-MMCS
You are currently using guest access (Log in)

Programming Fundamentals (Python)

  1. Home
  2. Courses
  3. Осенний семестр
  4. Python Eng
  5. Module 2: LOOPs
  6. Module 2.1 – The for Loop

Module 2.1 – The for Loop

Completion requirements

Python Programming: The for Loop

For English‑speaking students  |  Iteration, range(), and repetition

📑 Table of Contents

  • 🔹 Lab 3.1 – Print 10 Times
  • 🔹 Lab 3.2 – 0 to 9
  • 🔹 Lab 3.3 – 1 to 10
  • 🔹 Lab 3.4 – Even Numbers
  • 🔹 Lab 3.5 – Countdown
  • 🔹 Lab 3.6 – Sum 1 to n
  • 🔹 Lab 3.7 – Factorial
  • 🔹 Lab 3.8 – Count > 10
  • 🔹 Lab 3.9 – Star Rectangle
  • 🔹 Lab 3.10 – Star Triangle
  • 🔸 Practice Exercises
  • 🔸 Answer Key

Laboratory Works (3.1 – 3.10)

Each lab includes a step‑by‑step algorithm, solution code, and expected output. Max score: 1.0 per lab.

Lab 3.1 – Print "Python is awesome!" 10 Times

Score: 1.0

Task: Write a program that prints "Python is awesome!" 10 times.

📌 Algorithm

  1. Use range(10) to generate numbers 0 through 9.
  2. The loop runs 10 times.
  3. Each iteration prints "Python is awesome!".
  4. Use _ as the loop variable because we don't need its value.

💻 Solution Code


for _ in range(10):
    print("Python is awesome!")
                

📤 Expected Output

Python is awesome!
Python is awesome!
Python is awesome!
Python is awesome!
Python is awesome!
Python is awesome!
Python is awesome!
Python is awesome!
Python is awesome!
Python is awesome!
📖 Step‑by‑Step Explanation
  1. range(10) generates numbers 0 through 9.
  2. The loop runs 10 times, once for each number.
  3. Each iteration prints "Python is awesome!".
  4. We use _ because we don't need the loop variable.

Lab 3.2 – Print Numbers from 0 to 9

Score: 1.0

Task: Write a program that prints all numbers from 0 to 9, each on a new line.

📌 Algorithm

  1. Use range(10) to generate numbers 0 through 9.
  2. Each iteration, the loop variable i takes the next value.
  3. print(i) displays the current value.

💻 Solution Code


for i in range(10):
    print(i)
                

📤 Expected Output

0
1
2
3
4
5
6
7
8
9
📖 Step‑by‑Step Explanation
  1. range(10) generates numbers 0 through 9.
  2. Each iteration, i takes the next value from the range.
  3. print(i) displays the current value on a new line.

Lab 3.3 – Print Numbers from 1 to 10

Score: 1.0

Task: Write a program that prints all numbers from 1 to 10, each on a new line.

📌 Algorithm

  1. Use range(1, 11) to generate numbers 1 through 10.
  2. The stop value (11) is exclusive.
  3. Each iteration prints the current value of i.

💻 Solution Code


for i in range(1, 11):
    print(i)
                

📤 Expected Output

1
2
3
4
5
6
7
8
9
10
📖 Step‑by‑Step Explanation
  1. range(1, 11) generates numbers 1 through 10.
  2. The stop value (11) is exclusive, so 10 is the last number.
  3. Each iteration prints the current value of i.

Lab 3.4 – Print Even Numbers from 2 to 20

Score: 1.0

Task: Write a program that prints all even numbers from 2 to 20.

📌 Algorithm

  1. Use range(2, 21, 2) to generate even numbers 2, 4, 6, ..., 20.
  2. Start at 2, stop before 21, step by 2.
  3. Each value is printed.

💻 Solution Code


for i in range(2, 21, 2):
    print(i)
                

Alternative Solution (using if):


for i in range(2, 21):
    if i % 2 == 0:
        print(i)
                

📤 Expected Output

2
4
6
8
10
12
14
16
18
20
📖 Step‑by‑Step Explanation
  1. range(2, 21, 2) generates 2, 4, 6, ..., 20.
  2. Start at 2, stop before 21, step by 2.
  3. Each value is printed on a new line.

Lab 3.5 – Countdown from 5 to 1

Score: 1.0

Task: Write a program that prints a countdown from 5 to 1, then "Blast off!".

📌 Algorithm

  1. Use range(5, 0, -1) to generate 5, 4, 3, 2, 1.
  2. Each number is printed on a new line.
  3. After the loop, "Blast off!" is printed.

💻 Solution Code


for i in range(5, 0, -1):
    print(i)
print("Blast off!")
                

📤 Expected Output

5
4
3
2
1
Blast off!
📖 Step‑by‑Step Explanation
  1. range(5, 0, -1) generates 5, 4, 3, 2, 1.
  2. Each number is printed on a new line.
  3. After the loop finishes, "Blast off!" is printed.

Lab 3.6 – Sum of Numbers from 1 to n

Score: 1.0

Task: Write a program that reads a number n and calculates the sum of all numbers from 1 to n.

📌 Algorithm

  1. Read n from the user.
  2. Initialize total = 0.
  3. Loop i from 1 to n.
  4. Add i to total each iteration.
  5. Print the final sum.

💻 Solution Code


n = int(input("Enter n: "))
total = 0

for i in range(1, n + 1):
    total = total + i

print("Sum of 1 to", n, ":", total)
                

📤 Expected Output

Enter n: 10
Sum of 1 to 10 : 55
📖 Step‑by‑Step Explanation
  1. Read n from the user.
  2. Initialize total = 0.
  3. Loop i from 1 to n inclusive.
  4. Add i to total each iteration.
  5. Print the final sum.

Lab 3.7 – Factorial

Score: 1.0

Task: Write a program that reads a number n and calculates n! (factorial).

📌 Algorithm

  1. Read n from the user.
  2. Initialize factorial = 1 (neutral for multiplication).
  3. Loop i from 1 to n.
  4. Multiply factorial by i each iteration.
  5. Print the result.

💻 Solution Code


n = int(input("Enter n: "))
factorial = 1

for i in range(1, n + 1):
    factorial = factorial * i

print(n, "! =", factorial)
                

📤 Expected Output

Enter n: 5
5 ! = 120

Test: For n = 5: 1 × 2 × 3 × 4 × 5 = 120

📖 Step‑by‑Step Explanation
  1. Read n from the user.
  2. Initialize factorial = 1 (neutral for multiplication).
  3. Loop i from 1 to n.
  4. Multiply factorial by i each iteration.
  5. Print the result.

Lab 3.8 – Count Numbers Greater Than 10

Score: 1.0

Task: Write a program that reads 10 numbers and counts how many are greater than 10.

📌 Algorithm

  1. Initialize counter = 0.
  2. Loop 10 times.
  3. Read a number each iteration.
  4. If the number is greater than 10, increment counter.
  5. Print the final count.

💻 Solution Code


counter = 0

for i in range(10):
    num = int(input("Enter number " + str(i + 1) + ": "))
    if num > 10:
        counter = counter + 1

print("Count of numbers greater than 10:", counter)
                

📤 Expected Output

Enter number 1: 5
Enter number 2: 12
Enter number 3: 8
Enter number 4: 15
Enter number 5: 3
Enter number 6: 20
Enter number 7: 7
Enter number 8: 11
Enter number 9: 9
Enter number 10: 14
Count of numbers greater than 10: 5
📖 Step‑by‑Step Explanation
  1. Initialize counter = 0.
  2. Loop 10 times, reading a number each time.
  3. If the number is greater than 10, increment counter.
  4. Print the final count.

Lab 3.9 – Star Rectangle

Score: 1.0

Task: Write a program that reads n and prints a rectangle of stars with n rows and 19 columns.

📌 Algorithm

  1. Read n from the user.
  2. Loop n times.
  3. Each iteration prints 19 stars.
  4. "*" * 19 creates a string of 19 stars.

💻 Solution Code


n = int(input("Enter n: "))

for _ in range(n):
    print("*" * 19)
                

Alternative Solution (using nested loops):


n = int(input("Enter n: "))

for _ in range(n):
    for _ in range(19):
        print("*", end="")
    print()
                

📤 Expected Output (n = 3)

Enter n: 3
*******************
*******************
*******************
📖 Step‑by‑Step Explanation
  1. Read n from the user.
  2. Loop n times.
  3. Each iteration prints 19 stars.
  4. "*" * 19 creates a string of 19 stars.

Lab 3.10 – Star Triangle

Score: 1.0

Task: Write a program that reads n and prints a right-aligned star triangle with n rows.

📌 Algorithm

  1. Read n from the user.
  2. Outer loop: i goes from 1 to n (rows).
  3. Inner loop: j goes from 0 to i-1 (stars in row).
  4. Each row has i stars.
  5. print() moves to the next line after each row.

💻 Solution Code


n = int(input("Enter n: "))

for i in range(1, n + 1):
    for j in range(i):
        print("*", end="")
    print()
                

📤 Expected Output (n = 5)

Enter n: 5
*
**
***
****
*****
📖 Step‑by‑Step Explanation
  1. Read n from the user.
  2. Outer loop: i goes from 1 to n (rows).
  3. Inner loop: j goes from 0 to i-1 (stars in row).
  4. Each row has i stars printed on the same line.
  5. print() moves to the next line after each row.

Lab 3.11 – Table of Numbers (n × 3)

Score: 1.0

Task: Print a table with n rows and 3 columns, all containing the number n.

📌 Algorithm

  1. Read n from the user.
  2. Outer loop runs n times (rows).
  3. Inner loop runs 3 times (columns).
  4. Print n each time, ending with a space.
  5. After each row, print() moves to the next line.

💻 Solution Code


n = int(input())
for i in range(n):
    for j in range(3):
        print(n, end=" ")
    print()
                

📤 Expected Output

Input: 8
Output:
8 8 8
8 8 8
8 8 8
8 8 8
8 8 8
8 8 8
8 8 8
8 8 8
📖 Step‑by‑Step Explanation
  1. Read n from the user.
  2. The outer loop runs n times, creating n rows.
  3. The inner loop runs 3 times, printing n with a space after each.
  4. After the inner loop completes, print() moves to the next line.

Lab 3.12 – Table of Row Numbers (n × 5)

Score: 1.0

Task: Print a table with n rows and 5 columns. The i-th row contains the number i.

📌 Algorithm

  1. Read n from the user.
  2. Outer loop: i goes from 1 to n.
  3. Inner loop: prints i five times.
  4. After each row, move to the next line.

💻 Solution Code


n = int(input())
for i in range(1, n + 1):
    for j in range(5):
        print(i, end=" ")
    print()
                

📤 Expected Output

Input: 3
Output:
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
📖 Step‑by‑Step Explanation
  1. Read n from the user.
  2. The outer loop iterates i from 1 to n, representing each row.
  3. The inner loop prints i five times on the same line.
  4. After each row, print() moves to the next line.

Lab 3.13 – Random function

Score: 1.0

Task: Integers K > 0 and N ≥ 0 are given. K sequences of integers with N elements in each set are entered. The program has to output the number of odd elements in each sequence. .

Note: It is better to use random function to generate the numbers of sequences. But in this case you shouldn’t forget to print out the elements.

📌 Algorithm

  1. Import the random module
  2. Read input values
  3. Start the outer loop — iterate k times (from 1 to k), where each iteration represents one sequence.
  4. Initialize counters and a list for the current sequence: set odd_count to 0 and create an empty list sequence
  5. Start the inner loop — repeat n times to generate n random numbers for the current sequence.
  6. Generate a random number in the range [0, 9]
  7. Check if the number is odd (num % 2 != 0). If yes, increment odd_count and print the number
  8. Repeat steps

💻 Solution Code

import random
k = int(input("enter the quantity of the sequences: "))
n = int(input("enter the quantity of numbers within the sequences: ")
for i in range(1, k + 1):
  odd_count = 0 
  print(f"sequence #{i}")
  for _ in range(n):
          num = random.randint(0, 9)  
          print(num, end=" ")
          if num % 2 != 0:
            odd_count += 1
          
   print(f"result: {odd_count} odd elements")
   print()  # Пустая строка для красоты, чтобы отделить последовательности

📤 Expected Output

enter the quantity of the sequences:  
>>> 3
enter the quantity of numbers within the sequences 
>>> 5

seq #1 
4 9 3 3 7 result: 4 odd elements 
seq #2 
6 9 8 2 9 result: 2 odd elements 
seq #3 
5 1 7 3 6 result: 4 odd elements 
📖 Step‑by‑Step Explanation
  1. Import the random module
  2. Read input values
  3. Start the outer loop — iterate k times (from 1 to k), where each iteration represents one sequence.
  4. Initialize counters and a list for the current sequence: set odd_count to 0 and create an empty list sequence
  5. Start the inner loop — repeat n times to generate n random numbers for the current sequence.
  6. Generate a random number in the range [0, 9]
  7. Check if the number is odd (num % 2 != 0). If yes, increment odd_count and print the number
  8. Repeat steps

✏️ Practice Exercises (Independent Work)

Try these on your own. Almost each practice includes a hint. Score: 0.1-0.5 each.

Practice 1 – Print "Hello" 5 Times

Score: 0.1

Task: Write a program that prints "Hello" 5 times.

Hello
Hello
Hello
Hello
Hello
📖 Algorithm
  1. Use range(5) to loop 5 times.
  2. Each iteration prints "Hello".

Practice 2

Score: 0.2

Task: Given integers K and N (N > 0). Print the number K exactly N times.

Enter k: 7
Enter n: 4
result: 7 7 7 7      

Practice 3 – Print Numbers from 10 to 19

Score: 0.1

Task: Write a program that prints all numbers from 10 to 19, each on a new line.

10
11
12
13
14
15
16
17
18
19
📖 Algorithm
  1. Use range(10, 20) to generate numbers 10 through 19.
  2. Each iteration prints the current value.

Practice 4

Score: 0.2

Task: Given two integers A and B (A < B). Print all integers between A and B in ascending order, including A and B themselves.

Enter a: 3
Enter b: 7
Numbers: 3 4 5 6 7

Practice 5 – Print Odd Numbers from 1 to 19

Score: 0.2

Task: Write a program that prints all odd numbers from 1 to 19.

1
3
5
7
9
11
13
15
17
19
📖 Algorithm
  1. Use range(1, 20, 2) to generate odd numbers from 1 to 19.
  2. Each iteration prints the current value.

Practice 6 – Print Numbers from m to n with a step

Score: 0.2

Task: Write a program that reads two numbers m and n (where m ≤ n) and prints all numbers from m to n inclusive with a step = 3.

Enter m: 3
Enter n: 15
3
6
9
12
15
📖 Algorithm
  1. Read m and n.
  2. Use range(m, n + 1) to iterate.
  3. Print each value.

Practice 7

Score: 0.2

Task: Given two integers A and B (A < B). Print all integers strictly between A and B in descending order (excluding A and B).

Enter a: 3
Enter b: 8
Numbers: 7 6 5 4 

Practice 8

Score: 0.2

Task: Given a positive integer N. Print the first N terms of the arithmetic progression 1, 4, 7, 10, … using a for loop.

Enter n: 5 
result: 1 4 7 10 13

Practice 9

Score: 0.2

Task: Given a positive integer N. Print the first N terms of the arithmetic progression 80, 78, 76, 74, … using a for loop.

Enter n: 5 
result: 80 78 76 74 72

Practice 10

Score: 0.2

Task: Given a positive integer N. Print the first N terms of the geometric progression 1, 5, 25, 125, …

Enter n: 4 
result: 1 5 25 125

Practice 11 – Countdown with Stars

Score: 0.3

Task: Write a program that prints a countdown from n to 1, with that many stars on each line.

Enter n: 5
5 *****
4 ****
3 ***
2 **
1 *
📖 Algorithm
  1. Read n.
  2. Loop i from n down to 1 using range(n, 0, -1).
  3. Print i followed by "*" * i.

Practice 12 – Sum of Even Numbers

Score: 0.3

Task: Write a program that reads n and calculates the sum of all even numbers from 1 to n.

Enter n: 10
Sum of even numbers from 1 to 10: 30
📖 Algorithm
  1. Read n.
  2. Initialize total = 0.
  3. Use range(2, n + 1, 2) to iterate over even numbers.
  4. Add each to total.
  5. Print the sum.

Practice 13

Score: 0.3

Task: Given two integers A and B (A < B). Find the sum of all integers from A to B inclusive.

Enter a: 3
Enter b: 7
Sum: 25

Practice 14

Score: 0.3

Task: Given a positive integer N. Find the sum of the first N terms of the arithmetic progression 1, 3, 5, …

Enter n: 4 
sequence: 1 3 5 7
sum:  16

Practice 15

Score: 0.3

Task: Given two integers A and B (A < B). Find the product of all integers from A to B inclusive.

2
5
Product: 120

Practice 16 – Product of Odd Numbers

Score: 0.3

Task: Write a program that reads n and calculates the product of all odd numbers from 1 to n. Make it twise: using if statements and using custom loop step.

Enter n: 7
Product of odd numbers from 1 to 7: 105
📖 Algorithm
  1. Read n.
  2. Initialize product = 1.
  3. Use range(1, n + 1, 2) to iterate over odd numbers.
  4. Multiply each into product.
  5. Print the product.

Practice 17

Score: 0.3

Task: Given two integers A and B (A < B). Find the sum of the squares of all integers from A to B inclusive.

2
4
2^2 = 4  3^2 = 9  4^2 = 16
sum = 29

Practice 18 – Average of 10 Numbers

Score: 0.3

Task: Write a program that reads 10 numbers and calculates their average.

Enter number 1: 5
Enter number 2: 7
Enter number 3: 3
Enter number 4: 8
Enter number 5: 6
Enter number 6: 9
Enter number 7: 4
Enter number 8: 2
Enter number 9: 10
Enter number 10: 6
Average: 6.0
📖 Algorithm
  1. Initialize total = 0.
  2. Loop 10 times, read a number, add to total.
  3. Calculate average = total / 10.
  4. Print the average.

Practice 19 – Sum of Sequence (with Swap)

Score: 0.2

Task: Write a program that sums all integers from start to end inclusive. If the user enters start > end, swap them.

Enter start: 5
Enter end: 2
Sequence from 2 to 5: 2 3 4 5  Sum: 14
📖 Algorithm
  1. Read start and end.
  2. If start > end, swap them.
  3. Initialize total = 0.
  4. Loop from start to end, adding each number to total.
  5. Print the sum.

Practice 20 – Largest and smallest of 5 Numbers

Score: 0.2

Task: Write a program that reads 5 numbers and finds the largest and smallest.

Enter number 1: 12
Enter number 2: 7
Enter number 3: 23
Enter number 4: 9
Enter number 5: 15
Largest: 23 smallest: 7
📖 Algorithm
  1. Read the first number as largest.
  2. Loop for the remaining 4 numbers.
  3. If a number is greater than largest, update largest.
  4. Print largest.

Practice 21 - nested loops

Score: 0.2

Task: Calculate a function z(x,y) = x+2y for every x varying in the interval [5;10] and y varying in the interval [1;5]. You should use nested for loops.

z(x,y)= 5+2*1 = 7
z(x,y)= 5+2*2 = 9
z(x,y)= 5+2*3 = 11
z(x,y)= 5+2*4 = 13
z(x,y)= 5+2*5 = 15
z(x,y)= 6+2*1 = 8
z(x,y)= 6+2*2 = 10
z(x,y)= 6+2*3 = 12
z(x,y)= 6+2*4 = 14
z(x,y)= 6+2*5 = 16
z(x,y)= 7+2*1 = 9
...
      

Practice 22

Score: 0.1

Task: Calculate the function z(x,y) = x-y for every x varying in the interval [30;33] and y varying in the interval [1;5]. You should use nested for loops.

30-1=29
30-2=28
30-3=27
30-4=26
30-5=25
31-1=30
31-2=29
31-3=28
31-4=27
31-5=26
32-1=31
...
      

Practice 23

Score: 0.2

Task: The program must display the rows with the following sequences as in the example below. Use nested loops: the outer for loop must iterate over the columns, the inner for loop must iterate over the sequences within each row.

0 0 0 0 0 
1 1 1 1 1 
2 2 2 2 2 
3 3 3 3 3 
4 4 4 4 4 
5 5 5 5 5 
6 6 6 6 6 
7 7 7 7 7 
8 8 8 8 8 
9 9 9 9 9 

Practice 24

Score: 0.2

Task: The program must display the rows with the following sequences as in the example below. Use nested loops and custop step.

1 1 1 1 1 1
3 3 3 3 3 3
5 5 5 5 5 5
7 7 7 7 7 7
9 9 9 9 9 9
      

Practice 25 – Multiplication Table

Score: 0.3

Task: Write a program that reads n and prints the multiplication table for n (from 1 to 10).

Enter n: 5
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
📖 Algorithm
  1. Read n.
  2. Loop i from 1 to 10.
  3. Print n x i = n * i.

Practice 26 – Hollow Square

Score: 0.5

Task: Print a hollow square of size n.

Input: 5
Output:
*****
*   *
*   *
*   *
*****
📖 Algorithm
  1. Read n.
  2. For each row i and column j, print "*" if i is first/last row or j is first/last column.
  3. Otherwise print a space.

Practice 27 – Diamond Pattern

Score: 0.5

Task: Print a diamond pattern with n rows (odd number).

Input: 5
Output:
  *
 ***
*****
 ***
  *
📖 Algorithm
  1. Read n (must be odd).
  2. Upper half: loop i from 1 to n step 2, print spaces and stars.
  3. Lower half: loop i from n-2 down to 1 step -2, print spaces and stars.

Practice 28

Score: 0.5

Task: Integers K > 0 and N ≥ 0 are given. K sequences of integers with N elements in each set are entered. The program has to output a minimum and maximum elements in each sequence.

Note: It is better to use random function to generate the numbers of sequences. But in this case don’t forget to print out the elements.

enter the quantity of the sequences:  
>>>3
enter the quantity of numbers within the sequences 
>>>5

sequence #1 
4 9 5 4 8 min =4, max=9
 
sequence #2 
6 9 2 3 4 min =2, max=9 

sequence #3 
9 1 4 8 7 min =1, max=9 
      

Practice 29

Score: 0.3

Task: The user enters k (how many lines to print) and n (how many stars per line). For each line, generate n random numbers between 1 and 3. If the number is 1 or 2, print a star *. If it’s 3, print a dot .. Do not store anything — just print immediately.

Enter the number of lines: 
>>> 3
Enter the number of symbols per line: 
>>> 5
**.*.
***.*
.*.**
      
📖 Algorithm
  1. Read k and n from the user.
  2. Start the outer loop: repeat k times (each time is a new line).
  3. Inside the outer loop, start the inner loop: repeat n times.
  4. In the inner loop, generate a random number from 1 to 3.
  5. If the number is 3, print .; otherwise, print *. Use end="" so symbols stay on the same line.
  6. After the inner loop finishes, call print() with no arguments to move to the next line.

Practice 30 - Color Blocks Generator

Score: 0.3

Task: The user enters k (how many rows to print) and n (how many blocks per row).
For each block, generate a random number from 1 to 2.
If the number is 1, print [R] (Red). If it’s 2, print [B] (Blue).
Do not store anything — just print immediately.

Enter the number of rows: 
>>> 3
Enter the number of blocks per row: 
>>> 4
[R][B][R][R]
[B][B][R][B]
[R][R][R][B]
      
📖 Algorithm
  1. Read k and n from the user.
  2. Start the outer loop: repeat k times (each time is a new row).
  3. Inside the outer loop, start the inner loop: repeat n times.
  4. In the inner loop, generate a random number from 1 to 2.
  5. If the number is 1, print [R]; otherwise, print [B]. Use end="" so blocks stay on the same line.
  6. After the inner loop finishes, call print() with no arguments to move to the next row.

Practice 31 - Simple Weather Simulation

Score: 0.4

Task: The user enters k (how many days to simulate) and n (how many hourly checks per day).
For each hour, generate a random number from 1 to 3.
If the number is 1, print S (Sunny). If it’s 2, print C (Cloudy). If it’s 3, print R (Rainy).
At the end of each day, print how many times it was Sunny.
Count Sunny hours while simulating.

Enter the number of days: 
>>> 2
Enter the number of hourly checks per day: 
>>> 5
Day 1: S C R S C -> Sunny hours: 2

Day 2: C C S S S -> Sunny hours: 3
      
📖 Algorithm
  1. Read k and n from the user.
  2. Start the outer loop: repeat k times (each time is a new day).
  3. Inside the outer loop, set a counter sunny_count = 0.
  4. Start the inner loop: repeat n times (each time is one hourly check).
  5. In the inner loop, generate a random number from 1 to 3.
  6. If the number is 1, print S; if 2, print C; if 3, print R. Use end="" to keep symbols on the same line.
  7. If the symbol is S, increase sunny_count by 1.
  8. After the inner loop finishes, print the total count of Sunny hours for that day.
  9. Print an empty line to separate days.

Practice ? – Fibonacci Sequence

Score: 0.2

Task: Write a program that reads n and prints the first n numbers of the Fibonacci sequence: 1, 1, 2, 3, 5, 8, 13, ...

Enter n: 10
1
1
2
3
5
8
13
21
34
55

Hint: Start with a = 1, b = 1. Each next number is a + b.

📖 Algorithm
  1. Read n.
  2. Initialize a = 1, b = 1.
  3. Print first two numbers if n ≥ 1 and n ≥ 2.
  4. Loop from 2 to n-1: compute c = a + b, print c, update a, b = b, c.

🔑 Answer Key – Practice Exercises

Solutions for the independent practice exercises. Check your work after attempting them.

Practice 1 – Solution

for _ in range(5):
                print("Hello")

Practice 2 – Solution

for i in range(10, 20):
                print(i)

Practice 3 – Solution

for i in range(1, 20, 2):
                print(i)

Practice 4 – Solution

m = int(input("Enter m: "))
                n = int(input("Enter n: "))

                for i in range(m, n + 1):
                print(i)

Practice 5 – Solution

n = int(input("Enter n: "))
                total = 0

                for i in range(2, n + 1, 2):
                total = total + i

                print("Sum of even numbers from 1 to", n, ":", total)

Practice 6 – Solution

n = int(input("Enter n: "))
                product = 1

                for i in range(1, n + 1, 2):
                product = product * i

                print("Product of odd numbers from 1 to", n, ":", product)

Practice 7 – Solution

total = 0

                for i in range(10):
                num = int(input("Enter number " + str(i + 1) + ": "))
                total = total + num

                average = total / 10
                print("Average:", average)

Practice 8 – Solution

largest = int(input("Enter number 1: "))

                for i in range(2, 6):
                num = int(input("Enter number " + str(i) + ": "))
                if num > largest:
                largest = num

                print("Largest:", largest)

Practice 9 – Solution

n = int(input("Enter n: "))

                for i in range(n, 0, -1):
                print(i, "*" * i)

Practice 10 – Solution

n = int(input("Enter n: "))

                for i in range(1, 11):
                print(n, "x", i, "=", n * i)

Practice 11 – Solution

n = int(input("Enter a number: "))
                num = abs(n)
                total = 0

                while num > 0:
                total = total + num % 10
                num = num // 10

                print("Sum of digits:", total)

Practice 12 – Solution

n = int(input("Enter n: "))

                a = 1
                b = 1

                if n >= 1:
                print(a)
                if n >= 2:
                print(b)

                for _ in range(2, n):
                c = a + b
                print(c)
                a, b = b, c

Practice 13 – Solution

start = int(input("Enter start: "))
                end = int(input("Enter end: "))

                if start > end:
                start, end = end, start

                total = 0
                for i in range(start, end + 1):
                total = total + i

                print("Sum from", start, "to", end, ":", total)

📋 Quick Reference – The for Loop

Basic Structure

for variable in range(n):
    # code block – repeats n times

range() Variants

  • range(n) → 0, 1, ..., n-1
  • range(start, stop) → start, ..., stop-1
  • range(start, stop, step) → start, start+step, ...

Common Patterns

# Counter
counter = 0
for _ in range(n):
    if condition: counter += 1

# Sum
total = 0
for i in range(n): total += i

Key Points

  • • range(n) stops at n-1
  • • Use _ when you don't need the variable
  • • Always indent the loop body
  • • Always use : after the for statement
  • • Initialize accumulators before the loop

© 2026 Python Module – The for Loop  |  Keep iterating!

◄ Module 1.3 - Built‑in Functions, Strings & math Module
Module 2.2 - The while Loop and Digit Processing ►

Blocks

Skip Navigation

Navigation

  • Home

    • Site pages

      • My courses

      • Tags

    • My courses

    • Courses

      • Осенний семестр

        • Прикладная математика и информатика

        • Фундаментальная информатика и ИТ

        • Математика, механика

        • Педагогическое образование

        • Магистратура

          • Разработка мобильных приложений и компьютерных игр

        • Аспирантура

        • Вечернее отделение

        • Другое

        • Этика ИИ

        • ОНС-Н_1

        • Прогр-ММ-2

        • Прогр-ММ-1

        • АБиМ-ИИБ26

        • МСиТВ_АБМ_2026

        • Python Eng

          • General

          • Module 1: Basics and Conditions

          • Module 2: LOOPs

            • AssignmentModule 2.1 – The for Loop

            • AssignmentModule 2.2 - The while Loop and Digit Processing

          • Module 3: Strings and Slices

          • Topic 3

          • Topic 4

          • Topic 5

          • Topic 6

          • Topic 7

          • Topic 8

          • Topic 9

          • Topic 10

        • Экзамен ИКТ

        • ТестИИ

        • Информатика-Осень-ПМИ-2

        • Информатика-осень-ПМИ-1

      • Весенний семестр

        • Прикладная математика и информатика

        • Фундаментальная информатика и ИТ

        • Математика, механика

        • Педагогическое образование

        • Магистратура

          • Разработка мобильных приложений и компьютерных игр

        • Аспирантура

        • Вечернее отделение

        • Другое

      • Воскресная компьютерная школа

        • Пользователь компьютера плюс

        • Пользователь прикладных программ

        • Программирование I ступень

        • Программирование II ступень

        • Программирование III ступень

        • Архив

      • Воскресная математическая школа

        • Открытое тестирование РНОМЦ и мехмата ЮФУ

          • Открытое тестирование РНОМЦ и мехмата ЮФУ - 2026

          • Открытое тестирование РНОМЦ и мехмата ЮФУ - 2025

        • Олимпиадная математическая школа

        • Повышение квалификации

        • Доступная математика

        • Лаборатория математического онлайн-образования мех...

        • Осенняя универсиада

        • Научно-практическая конференция

        • ВМШ

          • ВМШ -2025

          • ВМШ - 2026

        • Летняя олимпиадная математическая школа РНОМЦ и ме...

      • Государственная итоговая аттестация

      • Дополнительное образование

      • Олимпиады

      • Видеолекции

      • Разное

      • Архив курсов

      • Заочная школа мехмата ЮФУ

Supplementary blocks

You are currently using guest access (Log in)
Python Eng
Data retention summary
Get the mobile app
Яндекс.Метрика