Python Series β Part 6: Loops in Python β Full Detailed Guide
π§ Objective:
- Python ke 2 primary loops:
for
andwhile
range()
ka use- Nested loops
- Infinite loop se bachne ke tareeke
- Real-world examples + practice questions
π Introduction
"Bhai imagine karo agar tumhe ek list ke 100 items ko print karna ho... kya 100 print() likhoge?
Nahi na! π
Isi liye Python me hote hain Loops β jo kaam baar baar karte hain bina code repeat kiye.
Aaj ke video me hum sikhenge Python ke Loops β real examples, deep concept aur end me kuch solid practice bhi milega!"
π Section 1: Why Loops?
"Agar koi kaam repeat karna ho β jaise 1 se 100 tak number print karna, ya har student ko βPassβ likhna β hum loop ka use karte hain.
Isse humara code chhota, readable aur efficient hota hai."
Example:
print("Hello")
print("Hello")
print("Hello")
Versus:
for i in range(3):
print("Hello")
π Section 2: For Loop
"For loop tab use hota hai jab hume pata ho ki hume kitni baar repeat karna hai."
for i in range(5):
print("i:", i)
π§ range(n)
:
range(5)
means0 to 4
range(start, end, step)
for more control
Examples:
for i in range(1, 6):
print(f"{i} x 2 = {i*2}")
names = ["Rahul", "Aman", "Simran"]
for name in names:
print("Hello", name)
π Section 3: While Loop
"Jab hume nahi pata kitni baar repeat karna hai, aur repeat karna hai jab tak koi condition true ho β tab use hota hai while loop."
count = 0
while count < 5:
print("Count is:", count)
count += 1
Important:
while
me hamesha condition update karna zaruri hai β warna infinite loop ban sakta hai.
Real Example:
password = ""
while password != "deathcode":
password = input("Enter password: ")
print("Access Granted β
")
π Section 4: Break, Continue, Pass
"Loops me teen powerful cheeze aur hoti hain:"
break
πΉ for i in range(10):
if i == 5:
break
print(i)
continue
πΉ for i in range(5):
if i == 2:
continue
print(i)
pass
πΉ for i in range(3):
pass # Will be implemented later
πͺ Section 5: Nested Loops
"Loop ke andar loop bhi chalta hai! Isse hum grids ya combinations bana sakte hain."
for i in range(1, 4):
for j in range(1, 4):
print(f"{i} x {j} = {i*j}")
Output:
1 x 1 = 1
1 x 2 = 2
...
3 x 3 = 9
π Section 6: Practice Time β Real Examples
"Ab kuch aise questions jinka answer tum YouTube comment section me likh sakte ho ya khud practice karo!"
β Practice 1:
Print numbers from 10 to 1 (reverse)
β Practice 2:
Print table of 7 using for loop
β Practice 3:
Ask user to enter numbers until they type 0, then show total sum
β Practice 4:
Print star triangle:
*
**
***
****
π Outro
"To bhai, loops ke bina programming adhuri hai β aur aaj tumne seekha
for
,while
,break
,continue
,nested loops
β sab kuch ek hi video me.Agle video me hum sikhenge Functions in Python β jahan hum apne khud ke tools banayenge!
Donβt forget to practice, aur agar kuch doubt ho to comment section me pooch lena! π₯"