Sitemap

While loop python with examples

2 min readFeb 6, 2024

--

While loops basically run or activate or deactivate on boolean statements for example

Its raining . I Will not go outside until the rain stops.

So we can say I will not go outside while raining.

In python we can say

raining = True
while raining:
x=str(input("Is it raining? for yes enter y for no enter n \n:"))
if x=='y':
print("I will not go outside")
elif x=='n':
raining= False

print("I will go outside")

So the loop will continue until we enter n . That means when the rain stop.

Get Mashiur Rahman’s stories in your inbox

Join Medium for free to get updates from this writer.

We can also break the loop without entering n here with “break”

raining = True
count=0
while raining:

x=str(input("Is it raining? for yes enter y for no enter n \n:"))
if x=='y':
print("I will not go outside")
elif x=='n':
print("I will go outside")
raining= False
count+=1
if count==3:
break
print(count)

So whatever the raining is true or false it will stop asking after three times

Another memory efficient way to work with loop is using yield. When we call yield it creates a generator function

Its efficient because it only works when needed and then pause again.

We can not directly add yield but we can use it inside function

This program tells the time in every second

from datetime import datetime
import time

def time_generator():
while True:
yield datetime.now()


for current_time in time_generator():
print(current_time)
time.sleep(1)

While loop is useful. Because we can continue the program for example we have book database. We can continue search until that match our book name.

While loop also used in video games, for example while health>0 user can continue the game.

--

--