For Loops in Python: How to Find Even and Prime Numbers

Consider the existing_usernames list from the previous article. It can be inefficient to singly print a custom message to each user.

For loops can be used to achieve tasks like this with fewer lines of code.

python for loop

For loops are used to work with iterables. An iterable is a collection of elements or items. This can be a list, tuple or dictionary.

Let’s say we have rolled out a new feature on the website and we would like to inform all the users of the website about it. We can simply send them a custom message.

Without the for loop, we’ll implement this task like this:

existing_users = ['john12', 'smith98', 'alison01']

print(f"Dear {existing_users[0]}, we've added the dark mode feature")
print(f"Dear {existing_users[1]}, we've added the dark mode feature")
print(f"Dear {existing_users[2]}, we've added the dark mode feature")
python f-strings

A more efficient way to implement this task is:

existing_users = ['john12', 'smith98', 'alison01']

delivered = []

for user in existing_users:
    print(f"Dear {user}, we've added the dark mode feature")
    delivered.append(user)
    
print('Messages delivered successfully')
python for loop

user is a placeholder for an element during an iteration.  An iteration is a cycle in a loop

During the first iteration, 'john12' is assigned to user and this variable can be used throughout that iteration.

For the next iteration, the next element in the list is assigned to the variable, user.

Notice how we added each user to a list after sending them a message. This is to keep things organized against the next section.

We also added a message after the loop which would only get printed if the for loop doesn’t run into an error. This message can be shown to the admin.

if Blocks in for Loops

If blocks can be included in for blocks and vice versa. Let’s say new registers have just signed up on the website. We want to print a message to these new users about the new feature.

We have all the users of the website in one list including new users. How do we differentiate between users who received the message previously and those who haven’t?

We can use the if statement to check for a user in the delivered list. If a user doesn’t appear in this list, we’ll send him/her a message about the new feature.

existing_users = ['john12', 'smith98', 'alison01','denver21', 'helsinki04']

for user in existing_users:
    if user not in delivered:
        print(f"Dear {user}, we've added the dark mode feature")
    delivered.append(user)
print('Messages delivered successfully')
python for loop

It can be seen from the output that the message was sent to only new users of the website.

Checking for Even Numbers

Even numbers are numbers that are divisible by 2. These numbers can be divided by 2 without remainder.

Say we have a list of numbers.  To get the even numbers:

  • We’ll create an empty list to store the even numbers
  • The for loop will iterate through the numbers in the list, one at a time
  • The if condition will test if a number is divisible by 2 i.e. gives no remainder when divided by 2.
  • If True, it is appended to the list of even numbers
  • This process is repeated till the loop gets to the last number in the list
  • The list of even numbers is printed after the loop
numbers = [23,32,9,16,54,77,39,25]

even_numbers = []

for num in numbers:
    if num % 2 == 0:
        even_numbers.append(num)
print(even_numbers)
python even numbers

The modulo operator is a kind of division that returns the remainder. 5%2 returns 1. 4%2 returns 0 because it is divisible by 2

We can also print the even numbers within a specified range. We only need to create a numerical list within that range before our loop.

Read: Create Numerical Lists in Python

Let’s find the even numbers between 1 and 20 inclusive

numbers = list(range(1,21))

even_numbers = []

for num in numbers:
    if num % 2 == 0:
        even_numbers.append(num)
print(even_numbers)
python even numbers

Checking for Prime Numbers

Prime numbers are numbers that can be only divided by 1 and itself. Prime numbers have only two factors. This is why 1 is not considered a prime number as it has only one factor which is 1.

Say we have a list of random numbers. To get the prime numbers:

  • We’ll create an empty list to store the primes
  • The for loop would iterate through the numbers in the random numbers list, one at a time
  • We’ll then create another empty list to store the factors of that number
  • To get the factors of a number, we’ll divide it by all numbers from 1 to that number. To get the factors of 5, we’ll divide 5 by 1,2,3,4 and 5.
  • Any division operation that results to zero is a factor. The divisor is appended to the factors list
  • After the inner loop, the if statement checks if the length of the factors list is 2 i.e the numbers has just two factors
  • This process is repeated for all numbers in the list of random numbers
  • After the loop, all prime numbers are printed to the console.
numbers = [23,32,9,16,54,77,39,25]

primes = []

for num in numbers:
    factors = []
    for div in range(1,num+1):
        if num%div == 0:
            factors.append(div)
    if len(factors) == 2:
        primes.append(num)
print(primes)
python prime numbers

We can also print the prime numbers within a specified range. We only need to create a numerical list within that range.

Let’s find the prime numbers between 1 and 20 inclusive

numbers = list(range(1,21))

primes = []

for num in numbers:
    factors = []
    for div in range(1,num+1):
        if num%div == 0:
            factors.append(div)
    if len(factors) == 2:
        primes.append(num)
print(primes)
python prime numbers

Summary

  • For loops can be used to achieve tasks with fewer lines of code
  • An iteration is a cycle in a loop
  • if blocks can be included in for loops to test conditions
  • for blocks can also be included in if blocks

No comments:

Powered by Blogger.