Member-only story

Loops in Python — While and For

Pytech Academy
4 min readAug 4, 2023
Photo by Tim Johnson on Unsplash

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…

--

--

Pytech Academy
Pytech Academy

Written by Pytech Academy

Python, web apps with Streamlit/Flask, AI/ML - Learn it all at Pytech Academy! Master coding and build projects in Python. #PytechAcademy

No responses yet