Code / Python for Beginners / Unit 3: Loops

for loops and range() for लूप और range()

Lesson 8 of 14 · about 14 minutes · Repeat a fixed number of times; add things up.

⚡ 0 XP

Step 1 of 2

for i in range()

repeat× 4

When you know how many times to repeat, use for with range():

  • range(5) gives 0, 1, 2, 3, 4 (five numbers, starting at 0)
  • range(1, 11) gives 1 to 10 (the end number is not included)
  • range(2, 11, 2) gives 2, 4, 6, 8, 10 (step of 2)

for i in range(1, 4): runs the block three times, with i being 1, then 2, then 3. No counter to update by hand, so no infinite loop.

Example
for i in range(1, 4):
    print("Round", i)
for n in range(2, 11, 2):
    print(n)

🎯 Challenge: Pahada (times table) +15 XP

Read a number n and print its times table from 1 to 10 with a for loop, in exactly this form: 7 x 1 = 7, 7 x 2 = 14, … 7 x 10 = 70.

Try twice to unlock the solution (0/2)

main.pyCtrl ⏎
Output

What your program prints appears here.

Checklist

Press Run to check your code.

  • Table of 7 from 1 to 10
  • Exactly ten lines
  • Works for 12
  • Uses a for loop
Lesson notes (text version)

1. for i in range()

When you know how many times to repeat, use for with range():

  • range(5) gives 0, 1, 2, 3, 4 (five numbers, starting at 0)
  • range(1, 11) gives 1 to 10 (the end number is not included)
  • range(2, 11, 2) gives 2, 4, 6, 8, 10 (step of 2)

for i in range(1, 4): runs the block three times, with i being 1, then 2, then 3. No counter to update by hand, so no infinite loop.

                for i in range(1, 4):
    print("Round", i)
for n in range(2, 11, 2):
    print(n)
              

Challenge: Pahada (times table)

Read a number n and print its times table from 1 to 10 with a for loop, in exactly this form: 7 x 1 = 7, 7 x 2 = 14, … 7 x 10 = 70.

2. Adding up in a loop

A classic pattern: start a total at 0 before the loop, and add to it inside the loop.

You can also keep a best so far: start at 0, and inside the loop replace it whenever you see something bigger with if runs > best: best = runs.

You can call input() inside a loop, so each round reads the next line of the Inputs box.

                total = 0
for day in range(1, 4):
    cups = int(input(f"Cups on day {day}: "))
    total = total + cups
print("Cups in 3 days:", total)
              

Challenge: Runs per over

First read how many overs. Then, in a for loop, read the runs scored in each over. Print Total runs: 33 and Best over: 12 for the overs 8, 12, 3 and 10. Keep the sum in total and the biggest over in best.

Search by task, format or tool name.