The Story That Explains Loops 🏭Loops समझाने वाली कहानी 🏭一个解释循环的故事 🏭
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.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(什么也不做)。掌握这五个,几乎所有重复任务都能搞定。forwhilebreak · continue · passThis 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)。
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)
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:。
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) 也只占几十个字节 —— 见下面输出的最后几行。
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")
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,它永远不包含在内。
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 की चेतावनी नहीं देते।
循环中用不到循环变量时,把它命名为 _。这是一个约定,意思是“我知道会得到一个值,但我忽略它”。读者一眼就懂你的意图,代码检查工具也不会警告变量未使用。
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.")
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")
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。
for vs while — When to Use Which ⚖️for बनाम while — कब कौन सा ⚖️for 与 while —— 何时用哪个 ⚖️
| 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) |
| 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" |
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。
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()
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!")
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)
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 = “这一轮我处理完了 —— 给我下一个。”
少量使用时两者都很清晰。如果循环里到处都是它们,考虑先过滤(推导式或守卫子句)。
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__)
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")
pass vs continue vs break — Not the Same Thing!pass बनाम continue बनाम break — एक जैसे नहीं!pass、continue 与 break —— 完全不同!
| KeywordKeyword关键字 | What it doesक्या करता है作用 | Effect on the loopLoop पर असर对循环的影响 |
|---|---|---|
| pass | Nothing at allकुछ भी नहीं什么也不做 | The loop carries on normally — the next line runsLoop सामान्य चलता है — अगली line चलती है循环照常进行 —— 下一行会执行 |
| continue | Skips the rest of this roundइस चक्कर का बाक़ी हिस्सा छोड़ता है跳过本轮剩余部分 | Jumps to the next item or condition checkअगले item या condition जाँच पर जाता है跳到下一项或下一次条件检查 |
| break | Leaves 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")
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 块都来自实际运行每个版本。
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")
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。
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())
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 轮,三层就是十亿轮。嵌套之前先想想有没有更聪明的办法 —— 用集合判断“在不在”、用字典查找,或用内置函数。
Common Loop Patterns You Will Use Forever 🧰Loop के आम Patterns जो हमेशा काम आएँगे 🧰会一直用到的常见循环模式 🧰
break stops early; for-else reports "not found".break जल्दी रोकता है; for-else "नहीं मिला" बताता है।break 提前停止;for-else 报告“未找到”。continue, or more compactly with a list comprehension.continue से, या list comprehension से और छोटे में।continue,或用更紧凑的列表推导式。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)
Common Traps and How to Avoid Them 🪤आम जाल और उनसे कैसे बचें 🪤常见陷阱及如何避免 🪤
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
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()
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 结束游戏循环。
Golden Rules 🏆सुनहरे नियम 🏆黄金法则 🏆
Six questions on loops. Pick an answer to see why.
Loops पर छह सवाल। जवाब चुनें और कारण देखें।
关于循环的六道题。选择答案查看解释。
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 的差一错误,绝不在遍历列表时修改它。