We’re going to explore something super cool in Python — Loops!
Loops help us repeat things without writing the same code again and again. Sounds fun, right? Let’s dive in! 🐍💻
🎯 What Is a Loop?
Imagine you want to say "Hello!" 5 times. Without a loop, you’d write:
print("Hello!")
print("Hello!")
print("Hello!")
print("Hello!")
That’s too much typing! 🤯
With a loop, you can do it in just 2 lines:
print("Hello!")
Boom! 💥 That’s the power of loops.
🔄 Types of Loops in Python
1. For Loop
Use this when you know how many times you want to repeat something.
print("I love Python!")
What does it do?
range(3)
gives numbers: 0, 1, 2 (3 numbers)i
is the counterIt prints "I love Python!" 3 times
2. While Loop
Use this when you want to repeat until a condition is false.
while count <= 5:
print("Count is:", count)
count = count + 1
What’s happening?
It keeps printing the value of
count
It stops when
count
becomes more than 5
🧠 Let’s Practice with a Fun Example!
Print numbers from 1 to 10:
Print "Python is cool" 4 times:
print("Python is cool")
🚨 Loop Tip: Don’t Forget to Stop!
If you’re using a while loop, make sure it has an end! Otherwise, it will keep running forever. 😱
Example of a bad loop (don’t do this!):
print("Oops!") # This will never stop!
🏁 Final Thoughts
Loops are like magic wands 🪄 — they help you repeat tasks easily and write less code. Practice a few loop problems every day, and you'll be a Python pro in no time! 💪🐍
🎉 Try These!
Print your name 5 times.
Print all even numbers from 2 to 20.
Count backwards from 10 to 1.
write a code to print Fibonacci series (Level 7)
Level 0 → 0The Fibonacci sequence starts with 0 and 1, and each next number is the sum of the previous two:
Level 1 → 1
Level 2 → 0 + 1 = 1
Level 3 → 1 + 1 = 2
Level 4 → 1 + 2 = 3
Level 5 → 2 + 3 = 5
Level 6 → 3 + 5 = 8
Level 7 → 5 + 8 = 13 (but usually you stop before it at level 7 if you're counting from 0)Let me know if you'd like the code to generate it (Python or another language)!
Keep practicing and remember — coding is like solving puzzles. The more you play, the better you get! 🧩✨
Happy Coding! 🚀
No comments:
Post a Comment