|

Python Loops – Repeating Tasks Efficiently

Introduction

Loops allow you to repeat a block of code to run for multiple times until certain criteria is met..

Example:

  • Print numbers 1 to 100
  • Show list of students
  • Process data

for Loop

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

Output:

0
1
2
3
4

range() Function

While using range we use the format below and just like if we keep 1 in start and 10 in stop and if we keep 1 in step it will go like 1,2,3,4 but if we use 2 in step then it will go like 2,4,6,8 .

range(start, stop, step)

Example:

Here nothing is written in step place so the default value will be 1 .

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

while Loop

count = 1while count <= 5:
print(count)
count += 1

Loop with Condition

number = 1while number <= 10:
if number % 2 == 0:
print(number)
number += 1

break Statement

for i in range(10):
if i == 5:
break
print(i)

continue Statement

for i in range(5):
if i == 2:
continue
print(i)

Mini Project: Multiplication Table

This is a example of a Multiplication table code where it prints the multiplication table of a number entered by user.

num = int(input("Enter a number: "))for i in range(1, 11):
print(num, "x", i, "=", num * i)

Nested Loops

The loop inside another loop is called nested loop.

for i in range(1, 4):
for j in range(1, 4):
print(i, j)

Common Mistakes

  • Infinite loops
  • Forgetting increment
  • Wrong indentation

Conclusion

Now you understand:

  • for loops
  • while loops
  • break
  • continue
  • Nested loops

You now have a strong Python foundation.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *