Topic 10: What are Loops in Python?

 What are Loops in Python?                              Quiz for LoopsπŸ‘‰

(Reading Time 5-7minutes)
In programming, loops are an essential concept that allows you to repeat a block of code multiple times. In Python, loops help reduce repetition and make programs more efficient and readable.

Instead of writing the same code again and again, loops let the computer do the repetition automatically.A loop is a programming structure that lets you repeat a block of code multiple times as long as a condition is true or for a specific number of iterations.

A loop is a control structure that executes a group of statements repeatedly as long as a given condition is true. When the condition becomes false, the loop stops executing.

Example:

print("Hello")
print("Hello")
print("Hello")

Instead of writing this three times, you can use a loop:

for i in range(3):
    print("Hello")
Python supports mainly two types of loops:

  1. while loop

  2. for loop

 1. while Loop

The while loop executes a block of code as long as a given condition is True. When the condition becomes false, the loop stops

Syntax:

while condition:
    # code to repeat

Example:

i = 1
while i <= 5:
    print("Count:", i)
    i = i + 1

Output:

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
  • The loop starts with i = 1

  • Runs while i <= 5

  • Increments i each time

  • Stops when i becomes 6

2. for Loop

The for loop is used to iterate over a sequence (like a list, tuple, string, or range).

Syntax:

for variable in sequence:
    # code to execute

Example:

for fruit in ["apple", "banana", "cherry"]:
    print(fruit)

Output:

apple
banana
cherry
QUIZ for LoopsπŸ‘‰

For Loop Using range()

The range() function is most commonly used with a for loop when you want to run a loop a specific number of times.

Syntax:

range(start, stop, step)
Parameter Description Example
start     Starting value (default = 0)     range(2, 5) → starts at 2
stop     Stops before this number     range(2, 5) → ends at 4
step         Interval between values (default = 1)     range(1, 10, 2) → 1,3,5,7,9

Example 1:

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

Output:

0
1
2
3
4

Example 2:

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

Output:

1
2
3
4
5

Example 3: (Using step)

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

Output:

1
3
5
7
9

Summary 

Python loops are useful tools that help you program more quickly, easily, and effectively. They help you do the same things over and over again without having to think about them, and they are a key part of every Python program.You can write cleaner, smarter, and more efficient code if you learn how to use for, while, and range().

πŸ‘ˆPREVIOUS                                                    QUIZ for Loops                     NextπŸ‘‰

Comments

Post a Comment

Popular posts from this blog

Topic1 :- What is Python Programming?

Topic2: -Why Python?

Topic7: What is Numpy?