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

Python: Loops

Mary Ngure 2026年09月13日 17:44 3 次阅读 来源:Dev.to

One thing I've started noticing as I learn Python is that computers are really good at doing repetitive tasks. Imagine being asked to print the numbers from 1 to 100 manually. Or process the scores of 50 students one by one. That would be exhausting for a human. For Python, however, repeating a task is exactly what loops are designed for. Loops allow us to run a block of code multiple times without having to write the same code over and over again. What is a Loop? A loop tells Python: "Keep doing this until we've finished." For example, instead of writing: print ( 1 ) print ( 2 ) print ( 3 ) print ( 4 ) print ( 5 ) We can use a loop: for number in range ( 1 , 6 ): print ( number ) Output: 1 2 3 4 5 Much cleaner. for Loops A for loop is useful when we want to go through a sequence of items. It repeats KNOWN number of times, or over a collections of items. That could be: numbers strings lists other collections of data For example: names = [ " Mary " , " John " , " Ann " ] for name in names : print ( name ) Output: Mary John Ann Python takes each item from the list, stores it temporarily in name , and runs the indented code. Using range() range() is particularly useful when working with numbers. for number in range ( 1 , 6 ): print ( number ) This prints numbers from 1 to 5 . One thing to remember is that the ending number is not included . It stops before the number So: range ( 1 , 6 ) means: 1, 2, 3, 4, 5 while Loops A while loop works a little differently. Instead of going through a known sequence, it keeps running as long as a condition is true . For example: count = 1 while count <= 5 : print ( count ) count += 1 Output: 1 2 3 4 5 Here, Python keeps asking: Is count <= 5 ? As long as the answer is True , the loop continues. The line: count += 1 is important because it changes the value of count . Without it, the condition would remain true and we'd create an infinite loop . When Should I Use for vs while ? A simple way I'm thinking about it is: Use a for loop when

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