今日已更新 166 条资讯 | 累计 20138 条内容
关于我们

while Loop, break & continue, Lists (Creation, Mutability, Methods, List Comprehension)

Tejas Shinkar 2026年06月20日 23:19 3 次阅读 来源:Dev.to

📌 Key Concepts Overview Concept One-Line Definition while loop Repeats code as long as a condition is True while True Infinite loop — needs break to stop break Immediately exits the loop continue Skips current iteration, moves to next List Ordered, mutable collection — heterogeneous elements allowed List Comprehension One-line way to build a list using a loop + condition List Mutability Lists can be changed in place — id() stays the same 🔁 Part 1 — while Loop The 3 Components (Critical Pattern) # 1. Initialisation 2. Condition 3. Increment/Decrement a = 1 # 1. Initialisation while a <= 10 : # 2. Condition print ( ' Devops ' ) a += 1 # 3. Increment # Without increment → INFINITE LOOP (condition never becomes False) How it works: Condition is checked before each iteration. As soon as it's False , the loop stops. Miss the increment/decrement → infinite loop (a real production hazard — can hang a script or burn CPU). while — Practical Patterns # Countdown (decrement) a = 10 while a > 0 : print ( ' Devops ' ) a -= 1 # Sum of 1 to 20 total = 0 a = 1 while a <= 20 : total += a a += 1 print ( total ) # 210 # Product (factorial-style) of 1 to 20 product = 1 a = 1 while a <= 20 : product *= a a += 1 print ( product ) # Pattern using while + string repetition str1 = ' Devops ' i = 0 while i < len ( str1 ): print ( str1 [ i ] * ( i + 1 )) i += 1 # D # ee # vvv # oooo # ppppp # ssssss for vs while — When to Use Which Use for Use while You know the iterable / number of repetitions You don't know how many times — depends on a condition Looping over list, string, range Retry logic, polling, waiting for a state # DevOps: retry logic — classic while True use case max_attempts = 5 attempt = 0 while attempt < max_attempts : print ( f ' Attempt { attempt + 1 } : Connecting to server... ' ) # if connection succeeds: break attempt += 1 while True — Infinite Loop Pattern # Always True — runs forever until break is hit # Used for: retry logic, polling, menu-driven scripts, password validati

本文内容来源于互联网,版权归原作者所有
查看原文