Updated August 23, 2023
Introduction to Loops in Python
Loops in Python are a fundamental programming construct that allows repeatedly executing a code block. There are two loops in Python: for loops and while loops. If you need to keep a block of code running as long as a specific condition is true, you can accomplish this with a while loop, We use for loops to iterate through a series of elements.
Table of Content
Importance of Loops in Python Programming
Loops are essential in Python programming to the extent that they allow for efficient and flexible code repetition. You can automate processes, iterate over data structures, and perform complex computations using loops. They make writing clear and understandable code possible, making Python programming more approachable for developers of all experience levels.
Flow Chart
For Loop in Python
Python employs the iterative for loop statement to execute a code block until it satisfies an arbitrary requirement. Many programmers widely use the highly versatile loop in Python, which can work with various data structures.
Syntax & Basic Structure of For Loops
for variable_name in sequence:
# code to execute
During each iteration, the “sequence” will store its elements in the “variable_name” variable. The group of items that combines as a “sequence” are what the loop will iterate over. The code inside the loop actively runs for each element in the sequence until the loop concludes.
Flow Chart
Iterating Over Lists, Tuples, & Strings
For Loops in Python can iterate over multiple data structures such as lists, tuples, and strings. Here’s an example of how to iterate over a list:
#1 Iterating Over a List
Example
fruits = ['strawberry', 'grapes', 'fig', 'kiwi']
for fruit in fruits:
print(fruit)
Output
Here, we have a “fruits” list consisting of four strings. The for loop actively iterates over each string in the list and prints it to the console. In each iteration of the loop initiated by the line “for fruit in fruits,” the variable “fruit” is assigned to each item in the list of “fruits.” Subsequently, the line “print(fruit)” is executed during each iteration, actively displaying the value of the “fruit” to the console.
#2 Iterating Over a Tuple
Example
colors = ('red', 'green', 'blue', 'yellow')
for color in colors:
print(color)
Output
In this example, the “colors” tuple consists of four strings. The for loop iterates over each string in the tuple and prints the results to the console. Every element in the “colors” tuple is assigned to the variable “color” for each iteration of the loop started by the “for color in colors” line. The value of “color” is then printed to the console by executing the “print(color)” line for each iteration.
#3 Itearting Over a String
Example
message = 'Hello, world!'
for char in message:
print(char)
Output
In the above example, the string “message” contains a message. The for loop iterates over each character in the string and actively prints it to the console. For each iteration of the loop started by the “for char in message” line, each character in the “message” string provides its value for the variable char. After that, during each iteration, the line “print(char)” actively executes and prints the value of the “char” to the console.
Using the range() Function in For Loops
Python has a built-in method called range() that creates a series of numbers. To iterate a given amount of times, it is used in conjunction with for loops. Here’s an instance:
Example
for i in range(5):
print(i)
The output of this code, which prints the numbers 0 to 4 on separate lines, is as follows:
Output
Using the enumerate() Function in For Loops
Another built-in Python function that enables you to iterate over an iterable object’s index and value is the enumerate() function. Here’s a picture to help:
Example
loops = ['For', 'While', 'Do While']
for index, loop in enumerate(loops):
print(index, loop)
The output from this code, which prints out each loop in the list along with its index, is as follows:
Output
Nesting For Loops
To iterate over nested data structures, for loops, allow nesting inside each other. Here’s a case in point:
Example
matrix = [[9,8,7], [6,5,4], [3,2,1]]
for row in matrix:
for num in row:
print(num)
The output of this code, which prints each number in the nested list on a separate line, is as follows:
Output
List Comprehensions With For Loops
List comprehension is a shorthand for creating lists in Python, and it can be faster and more readable than traditional list creation loop methods.
It is a powerful technique for creating a new list by executing some operation on each item in an existing list. The resulting list gets created with a single line of code, making it elegant and efficient.
The basic syntax for list comprehension is as follows.
Syntax
new_List= [expression for i in iterable if condition]
The expression here represents the operation we want to perform on each item in the iterable.
The item is the iterable’s element, and the condition is an optional filter to select specific items.
List comprehensions can also be used in conjunction with for loops to create a list based on the results of the loop. Assume we have a list of numbers and want to create a new list that only contains even numbers:
Example
numbers = [20, 19, 18, 17, 16, 15, 14, 13, 12, 11]
even_numbers = [x for x in numbers if x % 2 == 0]
print(even_numbers)
Output
In this example, the expression is x, the item is x in numbers, and the condition is if x % 2 == 0, which filters out all the odd numbers.
List comprehension is also helpful in performing more complex operations. Say, we encounter a list of strings and need to build a new list that contains the length of each string:
Example
strings = ["hello", "world", "python"]
string_lengths = [len(x) for x in strings]
print(string_lengths)
Output
In this example, the expression is len(x), which calculates the length of each string in strings.
List comprehension is a practical approach that enables the quick and efficiently creating of new lists. We can write concise and readable code that is easy to understand and maintain using list comprehension.
While Loop in Python
Python’s while loop actively functions as a control flow statement that enables the execution of a code block in response to a defined condition. While the condition specified in the loop header is true, the code block inside the while loop’s scope will keep running. The loop will end when the condition becomes false, and the code will move on to the following statement.
Syntax and Basic Structure of While Loops
The basic syntax of a while loop in Python is:
While condition:
# code block
“condition” refers to a boolean expression assessed before the code block runs. The code block executes, and the condition gets reassessed if true. This procedure keeps going until the condition becomes no longer true. Indent the code block to show it is a component of the loop.
Flow Chart
Creating Basic While Loops
Let’s begin with an example of a while loop counting from 1 to 5:
Example
x = 1
while x <= 5:
print(x)
x += 1
In the above example, “x” has a starting value of 1. The code block is executed considering the condition “x<= 5” is satisfied. The value of “x” is output by the print command, which is 1. Then, we use the “+=” operator to increase “x” by 1. Reevaluating the condition, “x” is now determined to be 2, so the loop is continued. The cycle continues until “x” equals 6; the loop ends when the given condition becomes false.
Output
Using the break Statement in While Loops
The “break” statement allows exiting a loop early, even if the condition specified in the loop header is still true. Here’s an instance:
Example
x = 1
while x <= 5:
if x == 3:
break
print(x)
x += 1
We included an “if” statement inside the loop. If the value of “x” is 3, the break statement gets executed, and the loop terminates immediately. The print statement inside the loop is not executed for “x=3”, so the output is:
Output
Using the continue Statement in While Loops
The continue statement skips the remaining block of code for the current iteration of the loop and starts the next iteration. Here’s an example:
Example
x = 0
while x < 5:
x += 1
if x == 3:
continue
print(x)
In this example, we use the continue statement to skip the iteration where x is 3. The output is:
Output
Nesting While Loops
You can nest one while loop inside another to carry out more challenging tasks. Here’s a simple example:
Example
x = 1
y = 1
while x <= 3:
while y <= 2:
print(f'x={x}, y={y}')
y += 1
y = 1
x += 1
We have two nested while loops in this example. The inner loop executes once during each outer loop iteration, while the outer loop repeats three times. The result is:
Output
Infinite Loops in Python
An infinite loop entails a program that runs indefinitely unless the program is interrupted, extruding a while loop with the condition that always evaluates to ‘True.’ Infinite loops can prove helpful in various circumstances, such as running background tasks, but misusing them can also lead to program crashes.
Here’s an example of an infinite loop:
Example
while True:
print("This is an infinite loop")
Output
The string “This is an infinite loop” will be printed indefinitely by this loop. Note that in an infinite loop, the program will not execute any code outside of the loop. You modify the code to include a break statement that will exit the loop when it meets a particular condition to stop an infinite loop.
Below is an example of an infinite loop that can be terminated with a break statement:
Example
while True:
user_input = input("Enter a number between 1 and 10: ")
if user_input.isdigit() and int(user_input) in range(1, 11):
print("You entered a valid number.")
break
else:
print("Invalid input. Please try again.")
Output
Here, the loop will continue to solicit input from the user until they input a number between 1 and 10. The break statement will terminate the loop once the user enters a valid number.
Loop Control Statements in Python
Python offers several control statements that let you alter how loops behave. These statements facilitate managing the execution flow inside loops and exit or skip iterations based on a few parameters.
One can change how loops typically execute their code using loop control statements. Statements like these give more control over how the code executes and changes how loops behave. They are applied to enhance the readability, simplify the program, and increase the code performance.
Using the break Statement
The break statement ends the loop early when the code block meets a particular trigger. It works to end a loop before all its elements have been iterated. When using the break statement, the program immediately leaves the loop and moves on to the statement afterward.
Example
for i in range(10):
if i == 5:
break
print(i)
Output
Uses
The break statement is commonly used to enhance code performance and to halt the execution of a loop when a particular condition is satisfied. Additionally, it is helpful when you want to leave a loop early based on user input or other outside variables.
Using the continue Statement
Utilize the continue statement to go to the next loop iteration and skip the current one. The current iteration of the loop ends when the continue statement gets executed, and the loop moves on to the following iteration.
Example
for i in range(10):
if i == 5:
continue
print(i)
Output
Uses
The continue statement skips particular loop iterations unrelated to the current task. It is commonly used when specific requirements must be met before the next iteration of the loop can begin executing actively.
Using the pass Statement
The pass statement serves as a stand-in when no action is required. Developers often adopt this technique to define a function or class without implementing it actively.
Example
for i in range(10):
if i == 5:
pass
print(i)
Output
Uses
The pass statement will prove helpful when you want to define a function or class but still need to implement it. It enables you to construct the framework of a code, which can then be filled in without introducing any errors.
Nested Loops in Python
Nested loops are loops inside loops in the Python programming language, where an inner loop repeats its code for each iteration of an outer loop. It lets us perform sophisticated calculations, automate challenging tasks, and iterate over complicated data structures.
By iterating over each element, nested loops enable developers to carry out more complicated operations on multi-dimensional data structures like matrices or lists of lists. They also offer a method for carrying out conditional operations that depend on several variables.
Creating Basic Nested Loops
In Python, the inner loop’s start and end appear using indentation. For instance, let’s build a nested loop that prints out a multiplication table for numbers 1 through 5.
Example
for i in range(1, 6):
for j in range(1, 6):
print(i * j, end=' ')
print()
Output
Using Multiple Iterables in Nested Loops
Lists and dictionaries are examples of multiple iterables that can be used with nested loops. Here is an illustration that iterates over a list of names and a list of ages using nested loops:
Example
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
for name in names:
for age in ages:
print(name, age)
Output
Nesting While Loops
Like for loops, while loops in Python can also be nested. Here is a demonstration of printing a diamond shape using nested while loops.
Example
size = 5
i = 1
while i <= size:
j = 1
while j <= size - i:
print(' ', end='')
j += 1
j = 1
while j <= 2 * i - 1: print('*', end='') j += 1 print() i += 1 i = size - 1 while i >= 1:
j = 1
while j <= size - i:
print(' ', end='')
j += 1
j = 1
while j <= 2 * i - 1:
print('*', end='')
j += 1
print()
i -= 1
Output
Conditional Statements in Python
Conditional statements are a fundamental component of Python programming, allowing you to execute different instructions based on certain conditions. The if statement, the if-else statement, the if-elif-else statement, and nested conditional statements are just a few of the different types of conditional statements that Python supports. Furthermore, Python offers handy features for working with conditionals, such as short-circuit evaluation and the ternary operator.
Flow Chart
if Statement
The simplest conditional statement in Python is the if statement. It has the following syntax:
Syntax
if condition:
# code to be implemented if a condition is 'True'
Any expression that evaluates to a True or False boolean value can be used as the condition. The code block below the if statement will run if the condition is True. It will not run if the condition is False.
Flow Chart
Example
x = 5
if x > 3:
print("x is greater than 3")
Output
if-else Statement
The if-else statement enables executing one code block if the condition is ‘True’; another code block if the condition is ‘False.’ It has the following syntax:
Syntax
if condition:
# code to be implemented if condition is 'True'
else:
# code to be implemented if condition is 'False'
Flow Chart
Example
y = 2
if y > 3:
print("y > 3")
else:
print("y <= 3")
Output
if-elif-else Statement
The if-elif-else statement enables you to run various blocks of code by various conditions. It has the subsequent syntax:
Syntax
if condition1:
# code to be implemented if condition1 is 'True'
elif condition2:
# code to be implemented if condition2 is 'True'
else:
# code to be implemented if all conditions are 'False'
Flow Chart
Example
x = 4
if x > 5:
print("x > 5")
elif x > 3:
print("x > 3 but <= 5")
else:
print("x <= 3")
Output
Nested Conditional Statements
Nested conditional statements allow you to nest one conditional statement inside another. When you need to test various conditions, this can prove helpful. It has a distinctive syntax:
Syntax
if condition1:
# code to be implemented if condition1 is 'True'
if condition2:
# code to be implemented if condition2 is 'True'
else:
# code to be implemented if condition2 is 'False'
else:
# code to be implemented if condition1 is 'False'
Flow Chart
Example
x = 4
y = 6
if x > 3:
if y > 5:
print("Both x and y are greater than their respective values")
else:
print("x is greater than 3 but y is less than or equal to 5")
else:
print("x is either less than or equals to 3")
Output
Short-Circuit Evaluation
Python has a short-circuit evaluation feature that can make conditional statements more effective. The interpreter can forego evaluating the second operand if the outcome of the logical operators “and” and “or” can be inferred from the first operand. When the second operand is a complicated operation that is expensive to compute or might result in an error, this can save time and resources.
Example
x = 5
y = 0
if x > 3 and y != 0:
z = x / y
else:
z = None
print(z)
Output
The second operand of the “and” operator is never evaluated in this case because the condition “x > 3” is True, but the condition “y!= 0” is False. This avoids a possible divide-by-zero error.
Ternary Operator
The ternary operator is capable of helping create if-else statements more quickly. On a single line, you can use it to write a basic conditional statement. It has the subsequent syntax:
Syntax
value_if_true if condition else value_if_false
Example
x = 5
message = "x is greater than 3" if x > 3 else "x is less than or equal to 3"
print(message)
Output
Best Practices For Working With Conditional Statements
It’s critical to adhere to a few best practices when working with conditional statements in Python to produce readable, effective, and maintainable code. Here are a few tips:
- To make your code easy to read, define your variables clearly and descriptively.
- Avoid nested conditional statements when possible because they can be challenging to read and debug.
- Short-circuit evaluation can help your code run more quickly.
- Consider using the ternary operator for simple conditional statements that fit on a single line.
- Use comments to clarify the logic behind your conditional statements and other crucial information.
List Comprehension in Python
Python’s list comprehension feature is a clear and elegant way to make lists. By iterating over an existing list and manipulating the items, you can use this method to create a new list. List comprehension is a powerful Python feature that makes writing clear, compelling, and readable code easier.
You can make a new list by applying an expression to each item in an existing list or sequence. List comprehension replaces loops and conditional statements with a single line of code to make the code more readable and concise.
Basic Syntax and Structure of List Comprehensions
The input sequence, the output expression, and the optional conditional statement make up the basic syntax for list comprehension. The following is the structure of list comprehension:
Syntax
new_list = [expression for item in input_sequence if condition]
The output expression applies to each item in the input sequence and is referred to as “expression” in the syntax above. The variable “Item” stands for and holds the value of each item in the input sequence. The list or sequence on which list comprehension is carried out is taken as the “Input_sequence.” The optional conditional statement “Condition” filters the input sequence according to some standards.
Creating Basic List Comprehensions
Let’s take an example to create a basic list comprehension that squares the numbers in a list.
Example
# Create a list comprehension that squares the numbers in a list
num_list = [1, 2, 3, 4, 5]
squared_list = [num**2 for num in num_list]
print(squared_list)
Output
In the above, we have used the input sequence as “num_list”; the output expression is “num**2”, which squares each number in the list. We have not used any conditional statement, so it is a basic list comprehension.
Conditional List Comprehensions
Conditional list comprehension creates a new list based on some condition. It allows you to filter the input sequence based on some criteria and applies an expression to the remaining items. Let’s take an example to understand this.
Example
# Create a conditional list comprehension that filters even numbers from a list and squares them
num_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_squared_list = [num**2 for num in num_list if num % 2 == 0]
print(even_squared_list)
Output
Here, we have used the input sequence as “num_list”; the output expression is “num**2”, which squares each even number in the list. We have used a conditional statement “if num % 2 == 0” to filter the even numbers from the input sequence.
Uses
List comprehension is a powerful tool that can be used in various scenarios. Some common uses of list comprehension are:
- Creating a new list based on some criteria
- Filtering a list based on some condition
- Applying some operation to each item in a list
- Creating a list of tuples, dictionaries, or sets
Applications of Loops in Python
Loops have numerous uses in Python programming. They apply for data analysis, web scraping, task automation, animation creation, and other tasks. Loops have a powerful application in ML because they are used to actively train models by iterating over large datasets. Here are a few real-world examples of how loops in Python are likely to be adopted:
1. Processing Data
Loops are frequently used in data processing, such as reading data from a file or database and performing some operation on each item. Assume we have a list of numbers and want to use a loop to calculate their sum:
Example
numbers = [1, 2, 3, 4, 5]
sum = 0
for num in numbers:
sum += num
print("The sum is:", sum)
Output
2. Generating output
Loops can also apply to create output, such as a list of numbers or characters. A loop, for example, can be used to generate a list of the first ten even numbers:
Example
even_numbers = []
for i in range(1, 11):
even_numbers.append(i*2)
print("The first 10 even numbers are:", even_numbers)
Output
3. User Input
Loops are capable of helping handle user input, such as asking for input and waiting for a valid response. A loop, for example, can be used to prompt the user to input a number between 1 and 10:
Example
while True:
num = input("Enter a number between 10 and 20: ")
if num.isdigit() and int(num) >= 10 and int(num) <= 20:
break
print("You entered:", num)
Output
4. Web Scraping
Loops are also valuable for web scraping, extracting information from web pages. A loop, for example, can be used to extract the titles of all the articles on a web page:
Example
import requests
from bs4 import BeautifulSoup
url = "https://www.example.com/articles"
response = requests.get(url)
soup = BeautifulSoup(response.content, "html.parser")
titles = []
for article in soup.find_all("article"):
title = article.find("h2").get_text()
titles.append(title)
print("Article titles:", titles)
Output
These are a few instances of how Python loops may qualify as valuable. The possibilities are limitless, and they are a fundamental concept in Python programming capable of application in various ways.
When to Use Loops?
Python uses loops when a task needs implementation more than once. You can iterate over a list or array, perform calculations on a data set, or repeat a particular task a predetermined number of times. In addition, loops help automate processes, manipulate data, and perform intricate calculations.
Choosing the Right Loop For a Task
It’s essential to take into account,
- the type of data you’re working with
- the number of iterations needed
- the complexity of the computations being performed
when selecting the best loop for a task.
While loops help perform iterative calculations and loop until a certain condition is met. For loops are best for iterating over lists, tuples, and dictionaries. So, opting for the one that best fits your requirement or task is better.
Advantages and Disadvantages of For Loops and While Loops
The benefit of for loops is their clear syntax, making it simple to read and comprehend while iterating over data structures. Additionally, they are effective for tasks that call for a predetermined number of iterations. Loops can be less effective for tasks requiring dynamic iterations, such as looking for a specific value in a list.
Conversely, while loops are perfect for tasks that call for dynamic iterations or looping until a certain condition is met, they may be harder to read and write. Still, they offer more flexibility for difficult calculations. However, if the condition is not clearly defined, while loops can also be vulnerable to infinite loops.
Alternatives to Loops
While loops and for loops can sometimes not be the best solution for repetitive assignments in Python. List comprehensions, map(), filter(), and recursion are some alternatives. List comprehensions are succinct and effective for simple iterations, while map() and filter() offer strong data manipulation tools. Recursion proves helpful for complicated calculations that necessitate repeatedly calling a function.
Here are some examples of each Python alternative to loops:
1. List Comprehensions
As previously mentioned, list comprehensions are a clear and effective way to make lists in Python. They can also go through a sequence and adjust each item repeatedly. Here is another instance of how to make a list of squared numbers using list comprehension:
Example
squares = [y**2 for y in range(1, 10)]
print(squares)
Output
2. Map() and filter()
Python’s higher-order functions map() and filter() can transform and filter data. Using map() and filter(), the square of each odd number in a list can be determined as shown in the following example:
Example
numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x**2, filter(lambda x: x % 2 != 0, numbers)))
print(squares)
Output
In this instance, we first use filter() to narrow the list down to only odd numbers. Next, we compute the square of each odd number using a map(). Finally, we use the list() function to turn the result into a list.
3. Recursion
Recursion is a programming technique in which a function calls itself repeatedly until a specific condition, known as a base case, is met.Complex problems broken down into smaller, simpler problems are resolved using recursion. Here is a picture of how to compute a number’s factorial using recursion:
Example
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
print(factorial(5))
Output
In this case, a function called factorial() that accepts a number as an argument is defined. The function returns 1 (the default case) if the value is 0. The function keeps calling itself with the argument n-1 until the base case is reached if the number exceeds 0.
Tips and Tricks For Working With Loops
Working with loops can be challenging, especially when dealing with large data sets. Here are some tips to support your work more efficiently with loops.
#1 Avoiding Infinite Loops
Infinite loops can be a common problem when working with loops in Python. Here are some best practices to avoid infinite loops:
Use a break statement: Use a break statement in your loop to exit the loop if it meets the condition. For example
Example
while True:
x = input("Enter a number: ")
if x == "quit":
break
print(x)
Output
Set a maximum number of iterations: If you need clarification on how many times your loop should run, set a maximum number of iterations. For example
Example
for i in range(5):
x = input("Enter a number: ")
print(x)
Output
This will ensure that the loop will only run 5 times.
Use a boolean flag: Use a boolean flag to control the loop. For example:
Example
flag = True
while flag:
x = input("Enter a number: ")
if x == "quit":
flag = False
print(x)
Output
Test your loop with small inputs: Before running it with significant inputs, test it with small inputs to ensure it works correctly.
By following these practices, you can avoid infinite loops and ensure your loops run smoothly.
#2 Creating Efficient Loops
You must be efficient when using loops. Optimize your loops for performance if you want your code to run as quickly and fluidly as possible. Here are some strategies for developing more effective loops:
- Instead of manually creating a list of numbers, use the range() function. Performance can be enhanced, and memory can be saved.
- Reduce the number of operations carried out inside the loop. Reducing the number of operations can speed up your code because each one takes time.
- If you’re dealing with arrays or matrices, avoid using loops and instead use vectorized operations. Since vectorized operations are performance-optimized, they can be considerably faster than loops.
Example
numbers = [1, 2, 3, 4, 5]
squares = []
for num in numbers:
square = num ** 2
squares.append(square)
print(squares)
A more efficient option to accomplish the same thing is to use a list comprehension:
numbers = [1, 2, 3, 4, 5]
squares = [num ** 2 for num in numbers]
print(squares)
The above code is shorter, faster, and easier to read!
Output
#3 Debugging Loop Errors
Like any other programming language, loops in Python can cause errors if not implemented correctly. Here are some common Python loop errors and how to debug them:
- SyntaxError: Failing to close brackets or quotation marks or using incorrect syntax for the loop statement frequently causes this error.
- NameError: This error occurs when a loop variable is not defined or has not been assigned a value.
- TypeError: This error occurs when the loop’s data type is incorrect or incompatible with the task being performed.
- IndexError: This error occurs when the loop attempts to access an out-of-range index.
- ValueError: This error occurs when the value assigned to the loop variable is incompatible with the operation.
The following suggestions will aid you in improving your ability to debug loop errors:
- To see what is happening inside the loop, use print statements. To locate the error, print out the values of the variables at each step.
- Check your loop’s range. Your loop is probably iterating too frequently if you get an index out-of-range error.
- Divide your loop into smaller sections, and then test each section separately. This can accelerate the process of locating the error’s cause.
Consider that you have a list of strings and need to concatenate them and convert them into a single string. Here’s an example of a loop that’s causing an error:
Example
words = ['hello', 'world']
sentence = ''
for word in words:
sentence =+ word + ' '
The syntax error here is: the += operator should be used instead of =+. Here’s the corrected code:
words = ['hello', 'world']
sentence = ''
for word in words:
sentence += word + ' '
print(sentence)
Output
#4 Best Practices For Using Loops
When working with loops, following best practices to guarantee that your code is maintainable, readable, and error-free is essential. Here are some best practices for using loops:
- Use descriptive variable names to make your code more readable.
- Break your loops into smaller functions to make your program more modular and easier to test.
- Use comments to explain complex logic and improve readability.
Let’s take an instance where there is a list of numbers, and you need to find the sum of all the even numbers. Here’s an example of code that follows best practices:
Example
def sum_even_numbers(numbers):
"""
Takes a list of numbers & returns the sum of all even numbers.
"""
total = 0
for num in numbers:
if num % 2 == 0:
total += num
return total
# Define a list of numbers
numbers = [1, 3, 4, 15, 6, 21, 18, 29, 40]
# Call the function and pass the list as an argument
result = sum_even_numbers(numbers)
# Print the result
print(result)
This code explains what the function does with a docstring and a descriptive function name. Also, it separates the loop into its own function, making the code more modular and testable.
Let’s say you have the list of numbers as follows: [1, 3, 4, 15, 6, 21, 18, 29, 40]. If you pass this list to the sum_even_numbers() function, the output will be ’68’, the sum value of the even numbers in the given list (4 + 6 + 18 + 40).
Output
Recommended Articles
We hope that this EDUCBA information on “Loops in Python” was beneficial to you. You can view EDUCBA’s recommended articles for more information.