Skip to content

Write a program to print even numbers from 1 to 20 in Python

  • by

Printing even numbers from 1 to 20 in Python means to display all the integers between 1 and 20 (inclusive) that are divisible by 2 (i.e., the even numbers). Here’s how you can do it:

# Using a for loop to iterate through numbers from 1 to 20
for num in range(1, 21):
    # Check if the number is even
    if num % 2 == 0:
        # Print the even number
        print(num)

In this code:

  1. We use a for loop to iterate through the numbers in the range from 1 to 20.
  2. Inside the loop, we use the modulo operator % to check if the current number (num) is even. If num % 2 equals 0, it means the number is even.
  3. If the number is even, we print it to the console.

Program to print even numbers from 1 to 20 in Python

Here’s a Python program that prints even numbers from 1 to 20 using a while loop:

# Initialize a variable to start from 1
num = 1

# Use a while loop to iterate until num reaches 20
while num <= 20:
    # Check if the number is even
    if num % 2 == 0:
        # Print the even number
        print(num)
    
    # Increment num by 1 for the next iteration
    num += 1

Output:

Write a program to print even numbers from 1 to 20 in Python

In this code:

  1. We initialize a variable num to start from 1.
  2. We use a while loop to iterate until num reaches 20.
  3. Inside the loop, we check if the current value of num is even using the modulo operator %. If it’s even, we print it.
  4. After each iteration, we increment num by 1 to move to the next number in the sequence.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading