BASIC Python (Beginner Level) 📂 Basic Python Programming · 6 of 15 157 min read

Python Loops — for, while, break, continue & pass

Master Python loops from the ground up. This tutorial covers the for loop with animated flowcharts, the range() function, the while loop with condition-based iteration, when to choose for vs while, the break keyword to exit early, continue to skip iterations, pass as a do-nothing placeholder, the loop-else clause unique to Python, nested loops, four common loop patterns (accumulator, search, filter, map), common traps, and a full number-guessing game practice program.

🌐
SectionSection第 01 节

The Story That Explains Loops 🏭Loops समझाने वाली कहानी 🏭一个解释循环的故事 🏭

The Assembly LineAssembly Line流水线
Picture a car factory. One worker does not build each car by hand from scratch. Instead, an assembly line moves car frames, one after another, through the same stations: fit the engine, attach the doors, paint, test. A station does not care which car is in front of it; it does the same job again and again on whatever arrives next. That is a loop.

Programs are full of repetition: email every customer, add up every number in a list, keep asking for a password until it is right, draw frame after frame until the game ends. Without loops you would write each step by hand. With loops you write the job once and tell Python to repeat it.

Python has two loops — for (walk through a collection) and while (repeat while a condition holds) — plus three keywords that control them: break (leave early), continue (skip to the next round) and pass (do nothing). Learn these five and you can handle almost any repetition.
एक car factory सोचिए। एक मज़दूर हर car हाथ से शुरू से नहीं बनाता। इसकी जगह एक assembly line car के ढाँचे एक-एक करके उन्हीं stations से गुज़ारती है: engine लगाना, दरवाज़े लगाना, रंग करना, जाँच करना। Station को परवाह नहीं कि सामने कौन सी car है; वह अगली आने वाली पर वही काम बार-बार करता है। यही एक loop है।

Programs दोहराव से भरे होते हैं: हर customer को email, list की हर संख्या का जोड़, सही password मिलने तक पूछते रहना, game ख़त्म होने तक frame पर frame बनाना। Loops के बिना आप हर क़दम हाथ से लिखते। Loops के साथ आप काम एक बार लिखते हैं और Python से उसे दोहराने को कहते हैं।

Python में दो loops हैं — for (collection में चलना) और while (condition सही रहने तक दोहराना) — और उन्हें नियंत्रित करने वाले तीन keywords: break (जल्दी निकलना), continue (अगले चक्कर पर कूदना) और pass (कुछ न करना)। ये पाँच सीख लें तो आप लगभग हर दोहराव संभाल सकते हैं।
想象一家汽车工厂。工人不是从零开始手工造每辆车,而是让流水线把车架一个接一个地送过同样的工位:装发动机、装车门、喷漆、检测。工位不在乎面前是哪辆车,它对下一个到来的车重复做同样的工作。这就是循环。

程序里充满了重复:给每位客户发邮件、把列表里的每个数加起来、不停询问密码直到输对、一帧接一帧地绘制直到游戏结束。没有循环,你得把每一步都手写出来;有了循环,你只需把工作写一次,再让 Python 重复执行。

Python 有两种循环 —— for(遍历一个集合)和 while(条件成立时重复)—— 外加三个控制关键字:break(提前离开)、continue(跳到下一轮)和 pass(什么也不做)。掌握这五个,几乎所有重复任务都能搞定。
🔄
for
Walk through a collectionCollection में चलना遍历集合
"Do this for each item in that." Best when you know what you are walking through — a list, a range of numbers, the letters of a string.
"उसके हर item के लिए यह करो।" तब सबसे अच्छा जब पता हो कि आप किसमें चल रहे हैं — list, संख्याओं की range, string के अक्षर।
“对其中每一项做这件事。”最适合你清楚要遍历什么的时候 —— 列表、一串数字、字符串的字符。
⏳
while
Repeat while a condition holdsCondition रहने तक दोहराना条件成立时重复
"Keep doing this while something is true." Best when you do not know in advance how many rounds you need — waiting for input, retrying, simulating.
"जब तक कुछ सच है, यह करते रहो।" तब सबसे अच्छा जब पहले से पता न हो कि कितने चक्कर लगेंगे — input का इंतज़ार, दोबारा कोशिश, simulation।
“只要某件事为真,就一直做。”最适合事先不知道要几轮的时候 —— 等待输入、重试、模拟。
🛑
break · continue · pass
Control the flowप्रवाह नियंत्रित करें控制流程
break leaves the loop at once, continue skips to the next round, pass is a placeholder that does nothing.
break तुरंत loop छोड़ता है, continue अगले चक्कर पर कूदता है, pass कुछ न करने वाला placeholder है।
break 立即离开循环,continue 跳到下一轮,pass 是什么也不做的占位符。
▶️
How to Use the "Try It" Boxes"ख़ुद आज़माएँ" boxes कैसे इस्तेमाल करें如何使用“动手试试”框

This lesson has five live loop runners. Type a value in the yellow box, then press Step to run one line at a time, Play to watch the loop spin, or Run to jump to the end. In the flowchart the moving arrow is the path Python is taking now, and the purple loop-back arrow counts the rounds (×3, ×4…). The track shows each item: now, done, skipped (continue) or never reached (break).

इस lesson में पाँच live loop runners हैं। पीले box में मान लिखें, फिर एक-एक line चलाने के लिए Step, loop घूमते देखने के लिए Play, या सीधे अंत तक जाने के लिए चलाएँ दबाएँ। Flowchart में चलता तीर वह रास्ता है जिस पर Python अभी है, और बैंगनी वापसी तीर चक्कर गिनता है (×3, ×4…)। Track हर item दिखाता है: अभी, पूरा, छोड़ा (continue) या कभी नहीं पहुँचा (break)।

本课有五个循环运行器。在黄色框中输入一个值,然后点击单步逐行运行,点击播放观看循环转动,或点击运行直接跳到结尾。流程图中移动的箭头是 Python 当前走的路径,紫色回环箭头统计转了几轮(×3、×4……)。轨道显示每一项的状态:当前、完成、跳过(continue)或未到达(break)。


SectionSection第 02 节

The for Loop — Walking Through a Collection 🔄for Loop — Collection में चलना 🔄for 循环 —— 遍历集合 🔄

A for loop takes an iterable (anything you can walk through item by item) and runs its body once per item. The loop variable in for x in ... is bound to each item in turn.

for loop एक iterable लेता है (कुछ भी जिसमें item-दर-item चल सकें) और हर item के लिए अपनी body एक बार चलाता है। for x in ... का loop variable बारी-बारी हर item से बँधता है।

for 循环接收一个可迭代对象(任何能逐项遍历的东西),对每一项执行一次循环体。for x in ... 中的循环变量会依次绑定到每一项。

Basic Syntaxबुनियादी Syntax基本语法

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(f"I like {fruit}")

for letter in "hello":            # a string gives one character at a time
    print(letter, end=" ")
print()

for item in ("red", "green", "blue"):
    print(item, end=" ")
print()

scores = {"Asha": 92, "Ravi": 85}
for name in scores:               # a dict gives its keys
    print(f"{name}: {scores[name]}")

for n in {3, 1, 4, 1, 5}:         # a set has no duplicates and no fixed order
    print(n, end=" ")
print()

for i, fruit in enumerate(fruits, start=1):   # need a position too? use enumerate()
    print(i, fruit)
OUTPUT
I like apple I like banana I like cherry h e l l o red green blue Asha: 92 Ravi: 85 1 3 4 5 1 apple 2 banana 3 cherry
💡
Python's for Is a For-EachPython का for एक For-Each हैPython 的 for 是 for-each

Unlike C or Java, Python's for has no counter and condition. It is a for-each loop that walks through the items directly. Need a position too? Use enumerate(). Need numbers? Use range(). Avoid for i in range(len(lst)): just to read lst[i] — write for item in lst:.

C या Java के उलट, Python के for में counter और condition नहीं होते। यह एक for-each loop है जो सीधे items में चलता है। Position भी चाहिए? enumerate() लगाएँ। संख्याएँ चाहिए? range() लगाएँ। सिर्फ़ lst[i] पढ़ने के लिए for i in range(len(lst)): से बचें — for item in lst: लिखें।

与 C 或 Java 不同,Python 的 for 没有计数器和条件,它是直接遍历元素的 for-each 循环。还需要位置?用 enumerate()。需要数字?用 range()。不要只为了读 lst[i] 而写 for i in range(len(lst)): —— 直接写 for item in lst:。


SectionSection第 03 节

The range() Function — Your Number Companion 🔢range() Function — संख्याओं का साथी 🔢range() 函数 —— 数字好帮手 🔢

To loop a set number of times, or over a run of numbers, use range(). It produces numbers on demand instead of storing them, so even range(10_000_000) takes only a few dozen bytes — see the last lines of the output below.

तय बार loop करने, या संख्याओं के क्रम पर loop करने के लिए range() लगाएँ। यह संख्याएँ store करने की जगह ज़रूरत पर बनाता है, इसलिए range(10_000_000) भी सिर्फ़ कुछ दर्जन bytes लेता है — नीचे output की आख़िरी lines देखें।

要循环固定次数或遍历一串数字,就用 range()。它按需生成数字而不是把它们存起来,所以即使 range(10_000_000) 也只占几十个字节 —— 见下面输出的最后几行。

One argumentएक argument一个参数
range(stop)
0 up to, but not including, stop. range(5) → 0, 1, 2, 3, 4
0 से stop तक, पर stop शामिल नहीं। range(5) → 0, 1, 2, 3, 4
从 0 到 stop,但不含 stop。range(5) → 0, 1, 2, 3, 4
Two argumentsदो arguments两个参数
range(start, stop)
start up to, but not including, stop. range(2, 6) → 2, 3, 4, 5
start से stop तक, stop शामिल नहीं। range(2, 6) → 2, 3, 4, 5
从 start 到 stop,不含 stop。range(2, 6) → 2, 3, 4, 5
Three argumentsतीन arguments三个参数
range(start, stop, step)
The same, jumping by step. range(0, 10, 2) → 0, 2, 4, 6, 8
वही, पर step की छलांग से। range(0, 10, 2) → 0, 2, 4, 6, 8
同上,但每次跳 step。range(0, 10, 2) → 0, 2, 4, 6, 8
print(list(range(5)))
print(list(range(1, 6)))
print(list(range(0, 20, 3)))
print(list(range(10, 0, -1)))
print(list(range(5, 1)))          # start past stop → empty
for _ in range(3):
    print("Hello!")

import sys
big = range(10_000_000)
print(len(big), sys.getsizeof(big), "bytes")      # a range stores only start, stop, step
print(sys.getsizeof(list(range(1000))), "bytes for a list of just 1000")
OUTPUT
[0, 1, 2, 3, 4] [1, 2, 3, 4, 5] [0, 3, 6, 9, 12, 15, 18] [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] [] Hello! Hello! Hello! 10000000 48 bytes 8056 bytes for a list of just 1000
LIVELIVE互动range() Explorerrange() Explorerrange() 探索器

Move start, stop and step. Blue dots are the values range() gives, in order. The green ring is start; the red dashed line is stop, which is never included.

start, stop और step खिसकाएँ। नीले बिंदु वे मान हैं जो range() क्रम से देता है। हरा घेरा start है; लाल dashed रेखा stop है, जो कभी शामिल नहीं होता।

拖动 start、stop 和 step。蓝点是 range() 依次生成的值。绿圈是 start;红色虚线是 stop,它永远不包含在内。

🔑
Why Underscore? The "I Don’t Care" NameUnderscore क्यों? "मुझे फ़र्क़ नहीं पड़ता" वाला नाम为什么用下划线?“我不关心”的名字

When you loop but do not need the loop variable, name it _. It is a convention meaning "I know a value is given, but I ignore it." Readers see your intent at once, and linters do not warn about an unused variable.

जब loop करें पर loop variable की ज़रूरत न हो, तो उसका नाम _ रखें। यह परंपरा है जिसका मतलब है "मुझे पता है मान मिल रहा है, पर मैं उसे अनदेखा कर रहा हूँ।" पढ़ने वाला तुरंत इरादा समझ जाता है, और linters unused variable की चेतावनी नहीं देते।

循环中用不到循环变量时,把它命名为 _。这是一个约定,意思是“我知道会得到一个值,但我忽略它”。读者一眼就懂你的意图,代码检查工具也不会警告变量未使用。


SectionSection第 04 节

The while Loop — Repeat Until the Condition Ends ⏳while Loop — Condition ख़त्म होने तक दोहराएँ ⏳while 循环 —— 重复直到条件结束 ⏳

A while loop repeats as long as a condition stays True. Before each round Python checks the condition: True → run the body; False → leave the loop. You do not say how many times — you say when to stop.

while loop तब तक दोहराता है जब तक condition True रहे। हर चक्कर से पहले Python condition जाँचता है: True → body चलाओ; False → loop छोड़ो। आप यह नहीं बताते कि कितनी बार — आप बताते हैं कि कब रुकना है।

while 循环在条件保持 True 时不断重复。每一轮之前 Python 都会检查条件:True → 执行循环体;False → 离开循环。你不需要说执行几次 —— 只需说何时停止。

count = 5
while count > 0:
    print(f"T-minus {count}")
    count -= 1                    # MUST change — or the loop never ends
print("Liftoff!")

temperature = 100
while temperature > 25:
    temperature -= 15             # cool by 15 each step
    print(f"Now {temperature}°")
print("Cool enough.")
OUTPUT
T-minus 5 T-minus 4 T-minus 3 T-minus 2 T-minus 1 Liftoff! Now 85° Now 70° Now 55° Now 40° Now 25° Cool enough.

A classic use of while is checking input: keep asking until the answer is acceptable. Here the first answer was too short:

while का एक पुराना इस्तेमाल input जाँचना है: जवाब ठीक होने तक पूछते रहो। यहाँ पहला जवाब बहुत छोटा था:

while 的经典用法是校验输入:一直询问,直到答案合格。这里第一次的输入太短了:

password = ""
while len(password) < 8:
    password = input("Enter a password (8+ chars): ")
print("Password accepted")
OUTPUT
Enter a password (8+ chars): abc Enter a password (8+ chars): secret12 Password accepted
⚠️
The Infinite Loop Trapअनंत Loop का जाल无限循环陷阱

If nothing in the body ever makes the condition False, the loop runs forever and your program hangs (press Ctrl+C to stop it). Every while body must do something that moves toward the end — count down, update a value, or break on a signal. If you write while True:, make sure there is a break inside.

अगर body में कुछ भी condition को कभी False नहीं करता, तो loop हमेशा चलता है और program अटक जाता है (रोकने के लिए Ctrl+C दबाएँ)। हर while body को अंत की ओर ले जाने वाला कुछ करना चाहिए — गिनती घटाना, मान बदलना, या संकेत पर break। अगर आप while True: लिखते हैं, तो पक्का करें कि अंदर break हो।

如果循环体中没有任何东西让条件变为 False,循环就会永远运行,程序卡住(按 Ctrl+C 停止)。每个 while 循环体都必须做某件事让它走向结束 —— 递减计数、更新数值,或在收到信号时 break。如果写了 while True:,务必确保里面有 break。


SectionSection第 05 节

for vs while — When to Use Which ⚖️for बनाम while — कब कौन सा ⚖️for 与 while —— 何时用哪个 ⚖️

✅ Use for when…for तब लगाएँ जब…以下情况用 for……
Situationस्थिति情况Exampleउदाहरण例子
You have a collection to walk throughचलने के लिए collection है有一个要遍历的集合for item in items
You know the exact countसटीक गिनती पता है知道确切次数for i in range(10)
Each character of a stringString का हर अक्षर字符串的每个字符for c in text
Dict keys and valuesDict की keys और values字典的键和值for k, v in d.items()
A fixed number of retriesतय संख्या में दोबारा कोशिश固定次数的重试for _ in range(3)
⏳ Use while when…while तब लगाएँ जब…以下情况用 while……
Situationस्थिति情况Exampleउदाहरण例子
The number of rounds is unknownचक्करों की संख्या पता नहीं轮数事先未知Wait for valid inputसही input का इंतज़ार等待有效输入
It depends on outside stateबाहरी स्थिति पर निर्भर取决于外部状态Retry until a server answersServer जवाब दे तब तक दोबारा重试直到服务器响应
Simulate until stableस्थिर होने तक simulation模拟直到稳定Physics steps until at restरुकने तक physics steps物理模拟直到静止
Event or game loopEvent या game loop事件循环或游戏循环while running:
Reading until a stop valueरुकने वाले मान तक पढ़ना读到结束标记为止Until the user types "quit"जब तक user "quit" न लिखे直到用户输入 "quit"
💡
Rule of Thumbअंगूठे का नियम经验法则

If you can say "for each X in Y", use for. Looping over a list, string, dict or range always ends, because they have a fixed number of items. Use while when the stopping point depends on something you compute or observe during the loop.

अगर आप कह सकें "Y के हर X के लिए", तो for लगाएँ। List, string, dict या range पर loop हमेशा ख़त्म होता है, क्योंकि उनमें items की तय संख्या होती है। जब रुकने का पल loop के दौरान निकाली या देखी गई किसी चीज़ पर निर्भर हो, तब while लगाएँ।

如果能说成“对 Y 中的每个 X”,就用 for。遍历列表、字符串、字典或 range 总会结束,因为它们的元素个数是固定的。当停止的时机取决于循环过程中计算或观察到的东西时,才用 while。


SectionSection第 06 节

break — Leave the Loop at Once 🚪break — तुरंत Loop छोड़ें 🚪break —— 立即离开循环 🚪

break is the emergency exit. When Python reaches it, it jumps out of the loop right away — no more rounds, no more checks. Use it when you have found what you wanted, or when there is no point going on.

break आपातकालीन निकास है। Python के उस तक पहुँचते ही वह तुरंत loop से बाहर कूदता है — न और चक्कर, न और जाँच। इसे तब लगाएँ जब जो चाहिए वह मिल गया हो, या आगे बढ़ने का कोई फ़ायदा न हो।

break 是紧急出口。Python 一遇到它就立即跳出循环 —— 不再有下一轮,也不再检查条件。在找到想要的东西,或继续下去已无意义时使用它。

numbers = [4, 2, 7, 1, 9, 3, 6]
for n in numbers:
    if n == 9:
        print("Found 9!")
        break                     # stop looking — we're done
    print(f"Checking {n}...")

for i in range(3):
    for j in range(3):
        if j == 2:
            break                 # leaves only the INNER loop
        print(i, j, end="   ")
print()
OUTPUT
Checking 4... Checking 2... Checking 7... Checking 1... Found 9! 0 0 0 1 1 0 1 1 2 0 2 1

The second half shows that break leaves only the inner loop: the outer loop still runs all three times. The while True + break pattern is the standard way to repeat until the user says stop:

दूसरा हिस्सा दिखाता है कि break सिर्फ़ अंदर वाला loop छोड़ता है: बाहरी loop फिर भी तीनों बार चलता है। while True + break का pattern user के रुको कहने तक दोहराने का मानक तरीक़ा है:

后半部分说明 break 只离开内层循环:外层循环仍然完整地运行三次。while True + break 是“重复到用户说停为止”的标准写法:

while True:
    answer = input("Continue? (yes/no): ")
    if answer.lower() == "no":
        break                     # the only way out of while True
    print("Ok, once more...")
print("Goodbye!")
OUTPUT
Continue? (yes/no): yes Ok, once more... Continue? (yes/no): no Goodbye!

SectionSection第 07 节

continue — Skip to the Next Round ⏭️continue — अगले चक्कर पर जाएँ ⏭️continue —— 跳到下一轮 ⏭️

continue is the "skip this one" button. The rest of the current round is skipped, and the loop moves on to the next item (or, in a while loop, checks the condition again).

continue "इसे छोड़ो" वाला बटन है। इस चक्कर का बाक़ी हिस्सा छूट जाता है, और loop अगले item पर बढ़ता है (या while loop में condition फिर जाँचता है)।

continue 是“跳过这一个”按钮。本轮剩余部分被跳过,循环进入下一项(在 while 循环中则是重新检查条件)。

numbers = [5, -3, 8, -1, 4, -7, 2]
for n in numbers:
    if n < 0:
        continue                  # skip negatives
    print(f"Processing {n}")

words = ["apple", "", "  ", "banana", "cherry", ""]
for word in words:
    if not word.strip():          # empty or only spaces
        continue
    print(word.upper())

total = 0
for n in range(1, 11):
    if n % 2 != 0:
        continue                  # skip odd numbers
    total += n
print(total)
OUTPUT
Processing 5 Processing 8 Processing 4 Processing 2 APPLE BANANA CHERRY 30
💡
break vs continue — The One-Line Differencebreak बनाम continue — एक line का अंतरbreak 与 continue —— 一句话的区别

break = "I am done with the whole loop — get me out."
continue = "I am done with THIS round — give me the next one."
Both read well when used sparingly. If a loop fills up with them, consider filtering first (a comprehension or a guard clause).

break = "पूरे loop से काम ख़त्म — मुझे बाहर निकालो।"
continue = "इस चक्कर से काम ख़त्म — अगला दो।"
कम इस्तेमाल हों तो दोनों साफ़ पढ़ते हैं। अगर loop इनसे भर जाए, तो पहले filter करने पर विचार करें (comprehension या guard clause)।

break = “整个循环我都处理完了 —— 让我出去。”
continue = “这一轮我处理完了 —— 给我下一个。”
少量使用时两者都很清晰。如果循环里到处都是它们,考虑先过滤(推导式或守卫子句)。


SectionSection第 08 节

pass — The "Do Nothing" Placeholder 🤐pass — "कुछ न करो" वाला Placeholder 🤐pass —— “什么也不做”的占位符 🤐

pass does nothing at all. It exists because Python needs at least one statement in every block — an empty function, class, if or loop is a syntax error. pass says "there will be code here, just not yet."

pass कुछ भी नहीं करता। यह इसलिए है क्योंकि Python को हर block में कम से कम एक statement चाहिए — ख़ाली function, class, if या loop syntax error है। pass कहता है "यहाँ code आएगा, बस अभी नहीं।"

pass 什么也不做。它的存在是因为 Python 要求每个代码块至少有一条语句 —— 空的函数、类、if 或循环都是语法错误。pass 的意思是“这里以后会有代码,只是现在还没有”。

def send_email(recipient, message):
    pass                          # TODO: write this later — the program still runs


class Placeholder:
    pass                          # a legal, empty class


for n in range(10):
    if n % 2 == 0:
        pass                      # do nothing for evens (just a reminder)
    else:
        print(f"odd: {n}")

send_email("asha@example.com", "hi")
print(type(Placeholder()).__name__)
OUTPUT
odd: 1 odd: 3 odd: 5 odd: 7 odd: 9 Placeholder

Leave the block truly empty (a comment does not count) and Python refuses to run:

Block को सच में ख़ाली छोड़ें (comment नहीं गिना जाता) तो Python चलने से मना कर देता है:

如果代码块真的为空(注释不算),Python 会拒绝运行:

def todo():
    # nothing here yet

print("hello")
OUTPUT
File "l6b.py", line 4 print("hello") ^^^^^ IndentationError: expected an indented block after function definition on line 1

pass vs continue vs break — Not the Same Thing!pass बनाम continue बनाम break — एक जैसे नहीं!pass、continue 与 break —— 完全不同!

KeywordKeyword关键字What it doesक्या करता है作用Effect on the loopLoop पर असर对循环的影响
passNothing at allकुछ भी नहीं什么也不做The loop carries on normally — the next line runsLoop सामान्य चलता है — अगली line चलती है循环照常进行 —— 下一行会执行
continueSkips the rest of this roundइस चक्कर का बाक़ी हिस्सा छोड़ता है跳过本轮剩余部分Jumps to the next item or condition checkअगले item या condition जाँच पर जाता है跳到下一项或下一次条件检查
breakLeaves the loop completelyLoop पूरी तरह छोड़ता है完全离开循环The loop ends; its else block is skippedLoop ख़त्म; उसका else block छूट जाता है循环结束;它的 else 块被跳过
for n in range(5):
    if n == 2:
        pass                      # no effect
    print(n, end=" ")
print("  ← pass")

for n in range(5):
    if n == 2:
        continue                  # skip printing 2
    print(n, end=" ")
print("  ← continue")

for n in range(5):
    if n == 2:
        break                     # stop the loop
    print(n, end=" ")
print("  ← break")
OUTPUT
0 1 2 3 4 ← pass 0 1 3 4 ← continue 0 1 ← break
LIVELIVE互动pass · continue · break Comparatorpass · continue · break तुलनाpass · continue · break 对比器

Pick what happens when n == 2. The output and the else block come from really running each version.

चुनें कि n == 2 पर क्या हो। Output और else block हर version को सच में चलाकर मिले हैं।

选择 n == 2 时执行什么。输出和 else 块都来自实际运行每个版本。

n == 2


SectionSection第 09 节

The else Clause — Python’s Loop Superpower 🦸else Clause — Python Loop की महाशक्ति 🦸else 子句 —— Python 循环的超能力 🦸

Python loops can have an else block, which few other languages offer. It runs only if the loop finished without hitting break. That makes it perfect for "search, and report if not found".

Python loops में एक else block हो सकता है, जो कुछ ही दूसरी भाषाओं में मिलता है। यह तभी चलता है जब loop break से टकराए बिना ख़त्म हो। इसलिए यह "खोजो, और न मिले तो बताओ" के लिए एकदम सही है।

Python 的循环可以带一个 else 块,很少有其他语言提供这一功能。它只在循环没有遇到 break 而结束时执行,非常适合“搜索,找不到就报告”的场景。

numbers = [1, 3, 5, 7, 9]

for target in (4, 5):
    for n in numbers:
        if n == target:
            print(f"Found {target}!")
            break
    else:
        print(f"{target} not in the list")      # runs only when no break happened

i = 0
while i < 3:
    print(i)
    i += 1
else:
    print("Loop finished cleanly")
OUTPUT
4 not in the list Found 5! 0 1 2 Loop finished cleanly
💡
Read It as "no break"इसे "no break" पढ़ें把它读作“没有 break”

The name else confuses many people. A better way to read it: loop-else = "no break happened". It also runs when the loop ran zero times, because no break happened then either.

else नाम कई लोगों को उलझाता है। इसे पढ़ने का बेहतर तरीक़ा: loop-else = "कोई break नहीं हुआ"। Loop शून्य बार चले तब भी यह चलता है, क्योंकि तब भी कोई break नहीं हुआ।

else 这个名字让很多人困惑。更好的理解方式:循环的 else = “没有发生 break”。即使循环一次都没执行,它也会运行,因为同样没有发生 break。


SectionSection第 10 节

Nested Loops — Loops Inside Loops 🪆Nested Loops — Loops के अंदर Loops 🪆嵌套循环 —— 循环中的循环 🪆

You can put one loop inside another. The inner loop runs completely for each round of the outer loop. This is how you handle grids, tables and combinations.

आप एक loop को दूसरे के अंदर रख सकते हैं। अंदर वाला loop बाहरी loop के हर चक्कर में पूरा चलता है। Grids, tables और combinations ऐसे ही संभाले जाते हैं।

可以把一个循环放进另一个循环里。外层循环的每一轮,内层循环都会完整运行一遍。网格、表格和组合都是这样处理的。

for i in range(1, 4):
    for j in range(1, 4):
        print(f"{i}x{j}={i*j:2d}", end="  ")
    print()

grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in grid:
    for cell in row:
        print(cell, end=" ")
    print()

found = False
for i in range(3):
    for j in range(3):
        if i * j >= 4:
            found = True
            break                 # leaves the inner loop
    if found:
        break                     # check the flag to leave the outer loop
print(f"Stopped at ({i}, {j})")


def find_pair():                  # cleaner: return leaves every loop at once
    for i in range(3):
        for j in range(3):
            if i * j >= 4:
                return i, j


print(find_pair())
OUTPUT
1x1= 1 1x2= 2 1x3= 3 2x1= 2 2x2= 4 2x3= 6 3x1= 3 3x2= 6 3x3= 9 1 2 3 4 5 6 7 8 9 Stopped at (2, 2) (2, 2)
⚠️
Nested Loops Grow FastNested Loops तेज़ी से बढ़ते हैं嵌套循环增长很快

Two nested loops over 1,000 items each is 1,000,000 rounds. Three is a billion. Before nesting, ask if there is a smarter way — a set for "is it in there?" checks, a dict lookup, or a built-in function.

1,000-1,000 items पर दो nested loops 10,00,000 चक्कर हैं। तीन हों तो एक अरब। Nesting से पहले पूछें कि कोई बेहतर तरीक़ा है या नहीं — "क्या यह अंदर है?" जाँच के लिए set, dict lookup, या कोई built-in function।

两层各 1,000 项的嵌套循环就是 1,000,000 轮,三层就是十亿轮。嵌套之前先想想有没有更聪明的办法 —— 用集合判断“在不在”、用字典查找,或用内置函数。


SectionSection第 11 节

Common Loop Patterns You Will Use Forever 🧰Loop के आम Patterns जो हमेशा काम आएँगे 🧰会一直用到的常见循环模式 🧰

💰
AccumulatorAccumulator累加器
running totalrunning total累计
Start with an "empty" value (0, "", []) and add to it each round. The base of sum, count and join.
"ख़ाली" मान (0, "", []) से शुरू करें और हर चक्कर में उसमें जोड़ें। sum, count और join की नींव।
从“空”值(0、""、[])开始,每轮往里加。它是求和、计数和拼接的基础。
🔍
SearchSearch搜索
find and stopखोजो और रुको找到即停
Walk until you find what you want. break stops early; for-else reports "not found".
जो चाहिए वह मिलने तक चलें। break जल्दी रोकता है; for-else "नहीं मिला" बताता है।
一直遍历直到找到目标。break 提前停止;for-else 报告“未找到”。
📋
FilterFilter过滤
keep a subsetकुछ हिस्सा रखो保留子集
Keep only items that match a condition — with continue, or more compactly with a list comprehension.
सिर्फ़ condition से मेल खाने वाले items रखें — continue से, या list comprehension से और छोटे में।
只保留满足条件的元素 —— 用 continue,或用更紧凑的列表推导式。
🔄
Map / TransformMap / Transform映射 / 变换
reshape each itemहर item बदलो变换每一项
Apply the same change to every item and collect the results. A list comprehension usually reads best.
हर item पर वही बदलाव करें और नतीजे इकट्ठा करें। आमतौर पर list comprehension सबसे साफ़ पढ़ता है।
对每一项做同样的变换并收集结果。列表推导式通常最易读。
numbers = [10, 20, 30, 40]
total = 0
for n in numbers:
    total += n
print(total, sum(numbers))

words = ["Python", "is", "fun"]
print(" ".join(words))

nums = [7, 3, 9, 12, 15]
for n in nums:
    if n % 2 == 0:
        print(f"First even: {n}")
        break
else:
    print("No even numbers")

data = [3, -1, 7, -4, 2, 0]
positives = [n for n in data if n > 0]
print(positives)

prices = [10.0, 20.0, 30.0]
with_tax = [p * 1.15 for p in prices]
print(with_tax)
OUTPUT
100 100 Python is fun First even: 12 [3, 7, 2] [11.5, 23.0, 34.5]

SectionSection第 12 节

Common Traps and How to Avoid Them 🪤आम जाल और उनसे कैसे बचें 🪤常见陷阱及如何避免 🪤

The infinite while loopअनंत while loop无限 while 循环
Forgetting to change the condition. while x > 0: print(x) runs forever if x never goes down. Check that the condition can become False.
Condition बदलना भूलना। x कभी कम न हो तो while x > 0: print(x) हमेशा चलता है। जाँचें कि condition False हो सकती है।
忘记改变条件。如果 x 从不减小,while x > 0: print(x) 会永远运行。确认条件最终能变为 False。
Off-by-one with range()range() में एक की चूकrange() 差一错误
range(5) gives 0…4, not 0…5. For 1 to 5 write range(1, 6). Stop is never included.
range(5) 0…4 देता है, 0…5 नहीं। 1 से 5 के लिए range(1, 6) लिखें। Stop कभी शामिल नहीं होता।
range(5) 给出 0…4,不是 0…5。要 1 到 5 请写 range(1, 6)。stop 永远不包含在内。
Changing a list while looping over itLoop करते हुए list बदलना遍历时修改列表
Removing items from the list you are looping over makes Python skip items (see below). Loop over a copy, lst[:], or build a new list.
जिस list पर loop कर रहे हैं उसमें से items हटाने पर Python items छोड़ देता है (नीचे देखें)। Copy lst[:] पर loop करें, या नई list बनाएँ।
从正在遍历的列表中删除元素会让 Python 跳过某些元素(见下文)。请遍历副本 lst[:],或构建新列表。
Changing a dict’s size while loopingLoop करते हुए dict का आकार बदलना遍历时改变字典大小
Adding or deleting keys mid-loop raises RuntimeError. Loop over list(d) or build a new dict.
Loop के बीच keys जोड़ने या हटाने पर RuntimeError आता है। list(d) पर loop करें या नई dict बनाएँ।
循环中增删键会引发 RuntimeError。请遍历 list(d) 或构建新字典。
Using the loop variable after the loopLoop के बाद loop variable इस्तेमाल करना循环结束后使用循环变量
After for i in range(5), i is still 4. If the loop ran zero times, i may not exist at all. Save what you need explicitly.
for i in range(5) के बाद i अब भी 4 है। Loop शून्य बार चला हो तो i शायद मौजूद ही न हो। जो चाहिए उसे साफ़-साफ़ save करें।
for i in range(5) 之后,i 仍然是 4。如果循环一次都没执行,i 可能根本不存在。需要的值请显式保存。
break in the wrong loopग़लत loop में breakbreak 跳错了循环
break leaves only the innermost loop. To leave nested loops, use a flag or move the loops into a function and return.
break सिर्फ़ सबसे अंदर वाला loop छोड़ता है। Nested loops छोड़ने के लिए flag लगाएँ या loops को function में रखकर return करें।
break 只离开最内层循环。要离开嵌套循环,用标志变量,或把循环放进函数里用 return。

Traps 3, 4 and 5, run for real. Notice that one 2 survives the "remove all even numbers" loop:

जाल 3, 4 और 5 असल में चलाए गए। ध्यान दें कि "सारी even संख्याएँ हटाओ" वाले loop से एक 2 बच जाता है:

陷阱 3、4、5 的真实运行结果。注意“删除所有偶数”的循环后还剩下一个 2:

nums = [1, 2, 2, 3, 4]
for n in nums:
    if n % 2 == 0:
        nums.remove(n)            # changing the list we are looping over
print(nums)                       # one 2 survived!

nums = [1, 2, 2, 3, 4]
print([n for n in nums if n % 2 != 0])   # build a new list instead

d = {"a": 1, "b": 2}
try:
    for k in d:
        d[k + "!"] = 0
except RuntimeError as err:
    print("RuntimeError:", err)

for i in range(5):
    pass
print(i)                          # the loop variable keeps its last value
OUTPUT
[1, 2, 3] [1, 3] RuntimeError: dictionary changed size during iteration 4

SectionSection第 13 节

Complete Practice Program — Number Guessing Game 🎯पूरा अभ्यास Program — संख्या पहचानो खेल 🎯完整练习程序 —— 猜数字游戏 🎯

This game uses every idea from the lesson. The session below is a real run: we fixed the random seed (random.seed(13)) so the secret numbers are 9 and then 10, and typed the guesses shown.

यह खेल lesson का हर विचार इस्तेमाल करता है। नीचे का session असली run है: हमने random seed तय किया (random.seed(13)) ताकि गुप्त संख्याएँ 9 और फिर 10 हों, और दिखाए गए अंदाज़े लिखे।

这个游戏用到了本课的所有概念。下面的对话是一次真实运行:我们固定了随机种子(random.seed(13)),让秘密数字依次为 9 和 10,并输入了所示的猜测。

# guessing_game.py — every loop concept in one program

import random

def get_valid_guess(low, high):
    """Loop until user enters a valid number (uses while + break)."""
    while True:                       # infinite loop with break exit
        raw = input(f"Guess ({low}-{high}): ")
        if not raw.strip():
            print("  Empty input — try again.")
            continue               # skip rest, ask again
        try:
            n = int(raw)
        except ValueError:
            print("  Not a number — try again.")
            continue
        if not low <= n <= high:
            print(f"  Out of range — must be {low}-{high}.")
            continue
        return n                     # valid — break out via return

def play_round(low, high, max_tries):
    """One round using a for loop with break and for-else."""
    secret = random.randint(low, high)
    print(f"\nI'm thinking of a number between {low} and {high}.")
    print(f"You have {max_tries} guesses.\n")

    for attempt in range(1, max_tries + 1):
        guess = get_valid_guess(low, high)

        if guess == secret:
            print(f"🎉  Correct! You got it in {attempt} {'try' if attempt == 1 else 'tries'}.")
            return True
        elif guess < secret:
            print(f"  Too low.  ({max_tries - attempt} guesses left)\n")
        else:
            print(f"  Too high. ({max_tries - attempt} guesses left)\n")
    else:                             # for-else: only runs if no break/return
        print(f"😕  Out of tries. The number was {secret}.")
        return False

def main():
    # Accumulator: track wins and losses
    wins, losses = 0, 0

    while True:
        won = play_round(low=1, high=20, max_tries=5)
        if won:
            wins += 1
        else:
            losses += 1

        again = input("\nPlay again? (y/n): ").strip().lower()
        if again != "y":
            break                     # exit the game loop

    print(f"\nFinal score: wins = {wins}, losses = {losses}")

if __name__ == "__main__":
    main()
REAL SESSION
I'm thinking of a number between 1 and 20. You have 5 guesses. Guess (1-20): 10 Too high. (4 guesses left) Guess (1-20): 5 Too low. (3 guesses left) Guess (1-20): abc Not a number — try again. Guess (1-20): 25 Out of range — must be 1-20. Guess (1-20): 9 🎉 Correct! You got it in 3 tries. Play again? (y/n): y I'm thinking of a number between 1 and 20. You have 5 guesses. Guess (1-20): 5 Too low. (4 guesses left) Guess (1-20): 15 Too high. (3 guesses left) Guess (1-20): 12 Too high. (2 guesses left) Guess (1-20): 8 Too low. (1 guesses left) Guess (1-20): 11 Too high. (0 guesses left) 😕 Out of tries. The number was 10. Play again? (y/n): n Final score: wins = 1, losses = 1
🎯
Every Concept, One Programहर विचार, एक Program所有概念,一个程序

while True with continue and return checks the input; for with range counts the attempts; for-else prints the out-of-tries message; counters accumulate wins and losses; and break ends the game loop.

continue और return के साथ while True input जाँचता है; range के साथ for कोशिशें गिनता है; for-else मौक़े ख़त्म होने का संदेश छापता है; counters जीत और हार जोड़ते हैं; और break game loop ख़त्म करता है।

带 continue 和 return 的 while True 负责校验输入;配合 range 的 for 统计猜测次数;for-else 打印次数用完的提示;计数器累计胜负;break 结束游戏循环。


SectionSection第 14 节

Golden Rules 🏆सुनहरे नियम 🏆黄金法则 🏆

🐍 Python Loops — 8 RulesPython Loops — 8 नियमPython 循环 —— 8 条法则
1
Prefer for when you can, while when you must. A for over a list, string, dict or range always ends. Use while only when the stopping point depends on what happens during the loop.
जहाँ हो सके for, जहाँ ज़रूरी हो while। List, string, dict या range पर for हमेशा ख़त्म होता है। while तभी लगाएँ जब रुकने का पल loop के दौरान होने वाली बातों पर निर्भर हो।
能用 for 就用 for,必须时才用 while。遍历列表、字符串、字典或 range 的 for 总会结束。只有当停止时机取决于循环中发生的事情时才用 while。
2
Every while body must move toward the end. Trace a few rounds by hand to be sure the condition can become False.
हर while body को अंत की ओर बढ़ना चाहिए। कुछ चक्कर हाथ से चलाकर पक्का करें कि condition False हो सकती है।
每个 while 循环体都必须朝结束推进。手动推演几轮,确认条件能变为 False。
3
range(stop) never includes stop. range(5) is 0–4. When unsure, try list(range(...)) in the REPL.
range(stop) में stop कभी शामिल नहीं। range(5) = 0–4। शक हो तो REPL में list(range(...)) आज़माएँ।
range(stop) 永远不包含 stop。range(5) 是 0–4。不确定时在 REPL 里试试 list(range(...))。
4
Never change a list or dict while looping over it. Build a new one with a comprehension, or loop over a copy.
Loop करते हुए list या dict कभी न बदलें। Comprehension से नई बनाएँ, या copy पर loop करें।
绝不在遍历时修改列表或字典。用推导式构建新的,或遍历副本。
5
break stops the loop, continue stops this round, pass does nothing. Three keywords, three different jobs.
break loop रोकता है, continue यह चक्कर रोकता है, pass कुछ नहीं करता। तीन keywords, तीन अलग काम।
break 停止循环,continue 停止本轮,pass 什么也不做。三个关键字,三种不同的作用。
6
break leaves only the innermost loop. Python has no break 2; use a flag or a function with return.
break सिर्फ़ सबसे अंदर वाला loop छोड़ता है। Python में break 2 नहीं है; flag या return वाला function लगाएँ।
break 只离开最内层循环。Python 没有 break 2;用标志变量或带 return 的函数。
7
Loop else means "no break happened". Use it for "searched and did not find it".
Loop else का मतलब "कोई break नहीं हुआ"। इसे "खोजा और नहीं मिला" के लिए लगाएँ।
循环的 else 意味着“没有发生 break”。用于“搜索过但没找到”的情况。
8
Use a comprehension when a loop only filters or transforms. [n * 2 for n in nums if n > 0] is shorter and clearer than the 4-line loop. Keep full loops for complex logic.
Loop सिर्फ़ filter या transform करे तो comprehension लगाएँ। [n * 2 for n in nums if n > 0] चार line के loop से छोटा और साफ़ है। जटिल logic के लिए पूरे loops रखें।
循环只做过滤或变换时,用推导式。[n * 2 for n in nums if n > 0] 比 4 行的循环更短更清晰。复杂逻辑再用完整的循环。
LIVELIVE互动Quick Checkछोटी जाँच小测验

Six questions on loops. Pick an answer to see why.

Loops पर छह सवाल। जवाब चुनें और कारण देखें।

关于循环的六道题。选择答案查看解释。

🧮
Key Takeawayमुख्य सीख核心要点

Use for to walk through a collection or a range(), and while when you repeat until something changes — making sure it does change. break leaves the loop, continue skips one round, pass holds a place, and a loop's else runs only when no break happened. Watch for off-by-one ranges and never change a list while looping over it.

Collection या range() में चलने के लिए for लगाएँ, और कुछ बदलने तक दोहराने के लिए while — यह पक्का करते हुए कि वह सच में बदले। break loop छोड़ता है, continue एक चक्कर छोड़ता है, pass जगह रखता है, और loop का else तभी चलता है जब कोई break न हुआ हो। Range में एक की चूक से सावधान रहें और loop करते हुए list कभी न बदलें।

遍历集合或 range() 用 for,需要重复到某件事改变时用 while —— 并确保它真的会改变。break 离开循环,continue 跳过一轮,pass 占位,循环的 else 只在没有发生 break 时执行。小心 range 的差一错误,绝不在遍历列表时修改它。

🐍 Try Python Yourself

Write, run and visualize Python step by step. No install needed.