Loops kya hote hain?
Agar hume ek hi kaam bar-bar karna hai to baar-baar likhne ki jagah hum loops ka use karte hain. Python me do main loops hote hain:
- for loop → repeat karne ke liye
- while loop → jab tak condition true ho tab tak
for Loop
for i in range(5):
print("Hello", i)
Output:
Hello 0
Hello 1
Hello 2
Hello 3
Hello 4
List ke saath for loop
fruits = ["apple", "banana", "mango"]
for fruit in fruits:
print("I like", fruit)
Output:
I like apple
I like banana
I like mango
while Loop
count = 1
while count <= 5:
print("Count:", count)
count += 1
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Loop Control Statements
break→ loop ko tod deta haicontinue→ current iteration skip karke next pe chala jata hai
Example (break):
for i in range(10):
if i == 5:
break
print(i)
Output:
0
1
2
3
4
Example (continue):
for i in range(5):
if i == 2:
continue
print(i)
Output:
0
1
3
4
Next Step
Ab seekhte hain Functions ke baare me.