Member-only story
Loops in Python — While and For
While loop:
In Python, a while loop is used to repeatedly execute a block of code as long as a certain condition is true. The loop will continue to run until the condition becomes false. It is essential to ensure that the condition eventually becomes false; otherwise, the loop will run indefinitely, resulting in an infinite loop.
The syntax of the while loop is as follows:
while condition:
# Code block to be executed while the condition is true
Below are a few examples of while loop implementation
Example 1: Incrementing and printing Numbers
# Printing sequence of numbers
num = 0
while num <= 10:
num = num + 1
print(num)
This code starts with num = 0
and then repeatedly increments num
by 1 and prints its value as long as num
is less than or equal to 10. The output will be:
1
2
3
4
5
6
7
8
9
10
11
Example 2: Summing Numbers up to n
# Sum of 'n' numbers
List = []
n = 0
while n < 10:
n = n + 1
List.append(n)
print(List)
print(sum(List))
In this example, the code initializes an empty list List
, starts with n = 0
, and then repeatedly increments n
by 1, adding the current value of n
to the list. The loop runs while n
is…