Master Python Loops in One Slide!" 🚀 for, while, range() simplified 💡 Perfect for Beginners!

🐍 Python Day 5: Loops in Python

🎯 Loops are used to repeat a block of code multiple times.

🔁 1. for Loop

✅ Used to iterate over a sequence (like list, string, range).


🧠 Syntax:

for variable in sequence:

    # code block


🧪 Example:

for i in range(5):

    print("Hello", i)


🖨️ Output:

Hello 0  

Hello 1  

Hello 2  

Hello 3  

Hello 4


🔁 2. while Loop

✅ Repeats as long as the condition is true.


🧠 Syntax:

while condition:

    # code block


🧪 Example:

count = 1

while count <= 5:

    print("Count is:", count)

    count += 1


🖨️ Output:

Count is: 1  

Count is: 2  

Count is: 3  

Count is: 4  

Count is: 5


🔄 range() Function:

range(start, stop, step)


✅ Example:

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

    print(i)

🖨️ Output: 1 3 5 7 9

———————————————————

⚠️ Important Notes:

range(n) gives numbers from 0 to n-1.

break exits the loop early.

continue skips the current iterations .


💪 Practice Exercises:

1. Print numbers from 1 to 10 using for loop.

2. Print even numbers from 1 to 20 using while loop.

3. Sum of first 10 natural numbers using a loop.

4. Use break to stop a loop when a condition is met.

5. Use continue to skip printing number 6 in a loop from 1 to 10.


Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.