Repeating Tasks Without Repeating Code

Repeating Tasks Without Repeating Code

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: for variable in sequence: # Code to repeat Enter fullscreen mode Exit fullscreen mode 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 for number in range(5): print(number) Enter fullscreen mode Exit fullscreen mode The Result: 0 1 2 3 4 Enter fullscreen mode Exit fullscreen mode What happens step by Step: Python reads the statement range(5), which produces the numbers 0, 1, 2, 3, and 4. The first value, 0, is assigned to the variable number. Python executes the indented code and prints: 0 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. 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 students = ["Faith", "Sheila", "Bryan", "Sharon"] for student in students: print(student) Enter fullscreen mode Exit fullscreen mode Example 3: Combining a for loop and conditional if statement 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)") Enter fullscreen mode Exit fullscreen mode Output: 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 Enter fullscreen mode Exit fullscreen mode 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: while condition: # Code to repeat Enter fullscreen mode Exit fullscreen mode 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. count = 1 while count = 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}") Enter fullscreen mode Exit fullscreen mode # 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}") Enter fullscreen mode Exit fullscreen mode 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!

Original Source

Read the full article at Dev →

KhanList aggregates and links to publicly available news content. We do not host full articles from third-party sources. Always verify important information with original sources.