Table of Contents

Print First 5 Natural Numbers Using a While Loop

Example Description
Print the first 5 natural numbers using a while loop, uses a counter variable to control the loop and increment it until the count reaches 5.

Introduction:

This Python code demonstrates how to use a while loop to print the first 5 natural numbers. A counter variable is initialized to 1 and incremented by 1 in each iteration until it reaches 5.

Code:

#Print first 5 natural numbers using while loop
count = 1
while count <= 5:
 print(count)
 count += 1

Logic:

1. Initialize the counter variable ‘count’ to 1.
2. Use a while loop to iterate until ‘count’ is less than or equal to 5.
3. Inside the while loop, print the current value of ‘count’.
4. Increment ‘count’ by 1 in each iteration.

Output:

>> 1

>> 2

>> 3

>> 4

>> 5