Today were going to talk about loops in Python the bread and butter of any programmer’s diet. But first, let’s start with a little story…
Once upon a time, I was working on this super-duper project that involved calculating the sum of all even numbers between 10 and 20. And you know what? It took me forever to write that code! Why? Because I didnt understand loops yet.
But no need to get all worked up, my friend today we’re going to learn about three types of loops in Python: ‘for’, ‘while’, and ‘elif’. Let’s dive right into it!
First up, the classic ‘for’ loop. This is your go-to guy when you need to iterate over a list or range of numbers. Heres an example:
# Define a list of numbers
numbers = [10, 20, 30]
# Initialize a variable to store the total sum
total = 0
# Use a 'for' loop to iterate through the list of numbers
for num in numbers:
# Add each number to the total sum
total += num
# Print the final total sum
print(total) # Output: 60
In this code snippet, we first define a list of numbers and initialize the variable ‘total’ to zero. Then, using our trusty friend ‘for’, we iterate over each number in the list and add it to the total. Finally, we print out the result!
Now lets talk about the ‘while’ loop this guy is a bit more versatile than his buddy ‘for’. He can be used for both counting and checking conditions. Here’s an example:
# Using a 'while' loop to iterate through a list
# 'while' loop is more versatile than 'for' loop as it can be used for both counting and checking conditions
i = 0 # Initializing counter variable to 0
total = 0 # Initializing total variable to 0
# Using 'while' loop to iterate through list
while i < len(numbers): # Loop will continue until counter variable is less than length of list
total += numbers[i] # Adding current number to total
i += 1 # Incrementing counter variable by 1 after each iteration
print(total) # Output: 60 - prints the final total after all numbers have been added together
In this code snippet, we first initialize a counter variable ‘i’ to zero and set our initial value for total. Then, using the ‘while’ loop, we check if ‘i’ is less than the length of our list (which ensures that we dont go out of bounds). Inside the loop, we add each number in the list at index ‘i’ to our running total. Finally, we increment the counter variable and print out the result!
Last but not least, the ‘elif’ loop this guy is a bit more obscure than his friends ‘for’ and ‘while’. Hes used for checking conditions within loops (hence the name else if). Here’s an example:
# Creating a list of numbers
numbers = [10, 20, 30]
# Initializing a variable to store the total sum
total = 0
# Using a 'for' loop to iterate through the list of numbers
for num in numbers:
# Checking if the current number is even by using the modulo operator
if num % 2 == 0:
# If the number is even, add it to the total sum
total += num
# Printing the final total
print(total) # Output: 40
In this code snippet, we first define our list of numbers and initialize the variable ‘total’ to zero. Then, using a ‘for’ loop, we iterate over each number in the list. Inside the loop, we check if the current number is even (using an ‘if’ statement). If it is, we add that number to our running total. Finally, we print out the result!
But wait theres more! Let me introduce you to a lesser-known technique for optimizing your loops: list comprehension. Here’s how it works:
# Using list comprehension instead of 'for' loop with an 'if' statement inside
# Declaring a variable 'total' and assigning it the sum of a list comprehension
# The list comprehension iterates through the list 'numbers' and checks if each number is even using the 'if' statement
# If the number is even, it is added to the list
# The sum() function then calculates the total of the list and assigns it to the variable 'total'
total = sum([num for num in numbers if num % 2 == 0])
# Printing the value of the variable 'total'
print(total) # Output: 40
In this code snippet, we first define our list of numbers. Then, using a list comprehension, we create a new list that contains only the even numbers from the original list (using an ‘if’ statement inside). Finally, we use the built-in function ‘sum()’ to calculate the total sum of all the elements in this new list.
Remember, practice makes perfect, so go ahead and try these examples out for yourself.