Write a python program to print first 20 natural numbers using while loop

1. Introduction

In this blog post, we will write a Python program to print the first 20 natural numbers using a while loop. This is a fundamental exercise in programming that helps beginners understand the concept of loops, particularly the while loop, which is an essential part of control flow in Python.

2. Program Steps

1. Initialize a counter variable.

2. Use a while loop to iterate until the counter reaches 20.

3. Print the current value of the counter in each iteration.

4. Increment the counter in each iteration.

3. Code Program

def print_first_20_natural_numbers():
    # Step 1: Initialize the counter
    counter = 1

    # Step 2: Loop until the counter reaches 20
    while counter <= 20:
        # Step 3: Print the current number
        print(counter)

        # Step 4: Increment the counter
        counter += 1

# Call the function
print_first_20_natural_numbers()

Output:

The output will be the numbers from 1 to 20 printed each on a new line.

Explanation:

1. The program starts by initializing a counter variable to 1, since natural numbers start from 1.

2. A while loop is used to execute the loop body as long as the counter is less than or equal to 20.

3. Inside the loop, the current value of counter is printed, which represents the natural number at that iteration.

4. After printing, the counter is incremented by 1 (counter += 1). This step is crucial to ensure that the loop progresses and eventually terminates when the counter exceeds 20.

This simple program demonstrates the usage of a while loop in Python to iterate over a range of numbers and perform actions at each step.


Comments