🪟 Windows TippsThe Gemini desktop app is now available for Windows(11.09.2026 um 17:06 Uhr)
🪟 Windows TippsAnnouncing new builds for 11 September 2026(11.09.2026 um 19:11 Uhr)
🪟 Windows TippsChild account not showing in Microsoft Family(11.09.2026 um 11:11 Uhr)
🪟 Windows TippsUnable to connect to localhost MySQL workbench(11.09.2026 um 14:07 Uhr)
⚠️ Malware / Trojaner / VirenWindows 11 just dropped the tool ransomware abused, Microsoft says don’t restore WMIC(10.09.2026 um 20:11 Uhr)
🪟 Windows TippsThe Gemini desktop app is now available for Windows(11.09.2026 um 17:06 Uhr)
🪟 Windows TippsAnnouncing new builds for 11 September 2026(11.09.2026 um 19:11 Uhr)
🪟 Windows TippsChild account not showing in Microsoft Family(11.09.2026 um 11:11 Uhr)
🪟 Windows TippsUnable to connect to localhost MySQL workbench(11.09.2026 um 14:07 Uhr)
⚠️ Malware / Trojaner / VirenWindows 11 just dropped the tool ransomware abused, Microsoft says don’t restore WMIC(10.09.2026 um 20:11 Uhr)

🔧 Programmierung 🕛 vor 1 Monat 6 Min Lesezeit
0

Repeating Tasks Without Repeating Code

↗ Quelle (dev.to)
🗣️ Stimme:
📑 Inhaltsübersicht




Using for and while loops in Python



Now that Python can make decisions, how do we apply those decisions repeatedly?



In the last article, we learned how to guide Python through multiple levels of decision-making using nested if statements. But making decisions is only part of what makes Python pretty powerful.



Picture this: You've just landed your first data analysis task. Your dataset contains 9,000 respondents, and you need to perform the same check on every single record. After writing the same line of code a few times, and dodging errors, you stop and think: There has to be a better way than copying and pasting this thousands of times... right?



There is. It's called a loop, and by the end of this article, you'll know exactly how to use one, and get that task done in a fraction of that time.






The FOR Loop



A for loop is used to repeat a block of code a specific number of times or to iterate over a sequence, such as a list, a string, or a range of numbers.



The general syntax of a for loop looks like this:




CODE
for variable in sequence:
# Code to repeat






Where;





  • for : Indicates the beginning of the loop


  • variable: Stores the current value during each repetition. You can name it anything meaningful (number, student, county, letter, etc.).


  • in: Tells Python to go through each item in the sequence.


  • sequence: The collection being looped over, such as a range(), list, or string.


  • : Marks the beginning of the loop body.


  • Indentation : Indicates code blocks that are in the loop. Everything indented below the for statement is repeated.



Example 1: Looping over a range




CODE
for number in range(5):
print(number)






The Result:




CODE
0
1
2
3
4






What happens step by Step:




  1. Python reads the statement range(5), which produces the numbers 0, 1, 2, 3, and 4.

  2. The first value, 0, is assigned to the variable number.


  3. Python executes the indented code and prints:


    CODE
    0


  4. Python returns to the top of the loop, assigns the next value (1) to number, and prints it, the process continues for 2, 3, and 4.


  5. Once there are no more values left in the range, the loop ends and the program moves to the next line of code.




A quick note about range()




You may have noticed that range(5) prints the numbers 0 to 4, not 5. That's because the value passed to range() is the stopping point, and Python does not include it. In other words, range(5) means start at 0 and stop before 5.




Example 2: Looping over a list




CODE
students = ["Faith", "Sheila", "Bryan", "Sharon"]
for student in students:
print(student)






Example 3: Combining a for loop and conditional if statement




CODE
temperatures = [22, 35, 18, 40, 29, 15, 33]

for temperature in temperatures:
if temperature > 30:
print(f"Temperature is: {temperature}")
else:
print(f"Temperature is: {temperature} (below 30)")






Output:




CODE
Temperature is: 22 (below 30)
Temperature is: 35
Temperature is: 18 (below 30)
Temperature is: 40
Temperature is: 29 (below 30)
Temperature is: 15 (below 30)
Temperature is: 33






We've seen how for loops make it easy to repeat a block of code when we know what we're looping over, whether that's a range of numbers, a list, or another sequence. But what happens when we don't know in advance how many times a task needs to be repeated? That's where the while loop comes in.






The WHILE loop



The while loop repeatedly executes a block of code as long as a specified condition remains True. Once the condition becomes False, the loop stops.



The general syntax of a while loop looks like this:




CODE
while condition:
# Code to repeat






Where:





  • while: Indicates the start of the while loop


  • condition: The expression that evaluates to either True or False


  • : Marks the beginning of the loop body.


  • Indented code: The block of code that is repeatedly executed for as long as the condition remains True.



Let's see how this works in practice



Example 1: printing the numbers from 1 to 5.




CODE
count = 1

while count <= 5:
print(count)
count += 1






The Result:




CODE
1
2
3
4
5






What happens step by Step:




  1. The variable count is initialized with the value 1.

  2. Python checks the condition count <= 5. Since 1 is less than or equal to 5, the condition is True, so the loop begins.



  3. The statement print(count) is executed, displaying:


    CODE
    1


  4. The line count += 1 increases the value of count by 1, changing it from 1 to 2.


  5. Python returns to the top of the loop and checks the condition again. Since 2 <= 5 is still True, the loop repeats.


  6. This process continues until count becomes 6. At that point, the condition count <= 5 evaluates to False, so the loop stops and the program moves on to the next line of code.




Why do we need count += 1/count = count + 1?



Without this line, the value of count would never change. It would remain 1, meaning the condition count <= 5 would always be True. As a result, Python would keep printing 1 forever, creating an infinite loop.



For Example:




CODE
count = 1

while count <= 5:
print(count)






The Result:




CODE
1
1
1
1
1
...






The loop never ends because count is never updated. Since the condition always remains True, Python keeps executing the loop forever. This is called an infinite loop.

Every while loop should have a stopping condition so that it knows when to stop.



Let's do a few more examples that demonstrate how while loops are commonly used.




CODE
#Q1: You have a starting balance of 5k, and you are withdrawing 1000. So you can keep withdrawing as long as the balance is greater than withdrawal

mpesa_balance = 5000
withdrawn_amount = 1000
while mpesa_balance >= withdrawn_amount:
new_balance = mpesa_balance - withdrawn_amount
print(f"Request successful.Your new Balance is: Kshs: {new_balance}")
mpesa_balance -= 1000
print(f"You have insufficient funds. Your Balance is: Ksks: {new_balance}")









CODE
# Q2. A savings account starts with Ksh 1,000. It earns 10% interest every month. How many months does it take to reach Ksh 2,000? Print the balance each month.
start_amount = 1000
interest = start_amount * 0.1
month = 0

while start_amount <=2000:
interest = start_amount * 0.1
start_amount = interest + start_amount
month += 1
print (f"After {month} months, your interest is {interest}. The account balance is {start_amount}")









Conclusion



At the beginning of this article, we imagined having to process thousands of survey responses without writing the same code over and over again. As we've seen, loops provide a much more efficient solution.

Whether you use a for loop when you know what you're iterating over, or awhile loop when repetition depends on a condition, both allow Python to automate repetitive tasks efficiently and with far less effort and error than doing them manually.



As you continue learning, try modifying the examples in this article and create a few of your own. Remember, the more you practise, the more natural it will become to recognise when a loop is the right tool for the job.






Up Next...



We've learned how to repeat a single task. So far, our loops have executed until they naturally reached the end. In the next article, we'll learn how to stop a loop early or skip specific iterations using the break and continue statements. I look forward to sharing it with you!

Vollständiger Original-Bericht
Ausführliche Details, Code-Beispiele & Hersteller-Stellungnahme auf dev.to.
↗ Original-Artikel auf dev.to lesen
Wie bewertest du diesen Beitrag?
1 Klick Feedback
Teilen mit Netzwerk & Team:

Community-Analysen & Experten-Meinungen 0

Verfasse deine eigene Analyse, teile Workarounds oder diskutiere diesen Vorfall im Blog.
Noch keine Community-Analyse verfasst. Markiere einen Textabschnitt oder klicke oben auf Eigene Analyse verfassen“!
Community Pulse: Relevanz-Einschätzung
1 Klick Experten-Votum
🔴 Akute Relevanz 0%
🟡 In Evaluierung 0%
🟢 Keine Auswirkung 0%
Spannende Innovation 0%
Verwandte Story-Cluster & Quellen (Vektor-KI)
Port 8095 Engine
2 Quellen
The Gemini desktop app is now available for Windows
1 Quelle
Seamlessly import your team and data from Microsoft to Google Workspace during setup
1 Quelle
Announcing new builds for 11 September 2026
Ähnliche Beiträge
🔍 Verwandte News

Auch interessante Nachrichten Repeating Tasks Without Repeating Code

Thematisch verwandte Begriffe: Repeating, Tasks, Without, Code · 6 Treffer

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...