In Python programming, we use while loops to do a task a certain number of times repeatedly. The while loop checks a condition and executes the task as long as that condition is satisfied. The loop will stop its execution once the condition becomes not satisfied.
The syntax of a while loop is as follows:
while condition:
statements
In this post, I have added some simple examples of using while loops in Python for various needs. Check out these examples to get a clear idea of how while loops work in Python. Let’s dive right in.
1. Example of using while loops in Python
n = 1
while n < 5:
print("Hello Pythonista")
n = n+1
2. Example of using the break statement in while loops
In Python, we can use the break statement to end a while loop prematurely.
n = 1
while n < 5:
print("Hello Pythonista")
n = n+1
if n == 3:
break
3. Example of using the continue statement in while loops
In Python, we can use the continue statement to stop the current iteration of the while loop and continue with the next one.
n = 1
while n < 5:
if n == 2:
n = n+1
continue
print("Hello Pythonista")
n = n+1
4. Using if-elif-else statements inside while loop
z = 0
while z < 3:
if z == 0:
print("z is",z)
z += 1
elif z == 1:
print("z is",z)
z += 1
else:
print("z is",z)
z += 1
5. Adding elements to a list using while loop
myList = []
i = 0
while len(myList) < 4 :
myList.append(i)
i += 1
print(myList)
6. Python while loop to print a number series
n = 10
while n <= 100:
print(n ,end = ",")
n = n+10
7. Printing the items in a tuple using while loop
myTuple = (10,20,30,40,50,60)
i = 0
while i < len(myTuple):
print(myTuple[i])
i += 1
8. Finding the sum of numbers in a list using while loop
myList = [23,45,12,10,25]
i = 0
sum = 0
while i < len(myList):
sum += myList[i]
i += 1
print(sum)
9. Popping out elements from a list using while loop
fruitsList = ["Mango","Apple","Orange","Guava"]
while fruitsList:
print(fruitsList.pop())
print(fruitsList)
10. Printing all letters except some using Python while loop
i = 0
word = "Hello"
#print all letters except e and o
while i < len(word):
if word[i] == "e" or word[i] =="o":
i += 1
continue
print("Returned letter",word[i])
i += 1
11. Python while loop to take inputs from the user
n = int(input("Enter a number: "))
while n != 0:
n = int(input("Enter zero to quit: "))
12. Converting numbers from decimal to binary using while loop
num = int(input("Enter a number: "))
b = 0
p = 1
n = num
while n>0:
rem = n%2
b += rem * p
p = p*10
n = n//2
print("Binary value: ",b)
13. Finding the average of 5 numbers using while loop
p = 5
sum = 0
count = 0
while p > 0:
count += 1
f = int(input("Enter the number "))
sum += f
p -= 1
average = sum/count
print("Average of given Numbers:",average)
14. Printing the square of numbers using while loop
n = 1
while n <= 5:
squareNum = n**2
print(n,squareNum)
n += 1
15. Finding the multiples of a number using while loop
n = int(input("Enter an integer: "))
i = 1
while i <= 10:
mul = i*n
i += 1
print(mul)
16. Reversing a number using while loop in Python
n = int(input("Enter a number: "))
rev = 0
while n!=0:
r = n%10
rev = rev * 10 + r
n = n//10
print("Reversed number:",rev)
17. Finding the sum of even numbers using while loop
i = 0
sum = 0
n = int(input("Enter the number n: "))
while i <= n:
if i % 2 == 0:
sum += i
i += 1
print("Sum of even numbers till n:",sum)
18. Finding the factorial of a given number using while loop
n = int(input("Enter the number: "))
f =n
r = 1
while f != 0 :
r *= f
f -= 1
print("Factorial of",n,"is:",r)
I hope this article was helpful. Check out my post on 21 Python for Loop Examples.
I am looking for a way to take user inputs in while loop & compare it & print the smallest/largest value. Can you help?
9.) Popping out elements from a list using while loop
thank your us this kind of content for free appreciate 🙂
i was curious this # 9.)
fruitsList = [“Mango”,”Apple”,”Orange”,”Guava”]
while len(fruitsList) > 3:
fruitsList.pop()
print(fruitsList)
n=”e”
numlist = []
while n != “”
n= int(input (“Enter A Number: “))
numlist.append(n)
print(numlist)
print(max(numlist))
print (min(numlist))
Write a program that reads a value V, and then starts to read further values and adds them to a List until the initial value V is added again. Don’t add the first V and last V to the list. Print the list to the console.
Input Format
N numbers of lines input, with a random string
Output Format
Single line output, as a list.
Sample Input 1
56
23
346
457
234
436
689
68
80
25
567
56
Sample Output 1
[’23’, ‘346’, ‘457’, ‘234’, ‘436’, ‘689’, ’68’, ’80’, ’25’, ‘567’]
x = int(input(‘How many users will actually provide numerical values?’))
i = x
internal_list = []
def main(List:list!=None):
print(f”The given list of numerical entities is formed by {internal_list}”)
if i >= x:
print(f”The maximal value contained by user’ list is equal with… {max(internal_list)}”)
else:
pass
x = 1
while i >= x:
j: int = input(“Could you introduce your personal number?”)
internal_list.append(j)
x += 1
if i<=x:
main(List=internal_list)
break
You can append the numbers in the list and find the minimum or maximum.
i=0
newlist=[] #create an empty list
while i<5: #for 5 values
x=int(input(' Enter numbers'))
i+=1
newlist.append(x)
print(newlist) #you may skip this line
print("The smallest number is", min(newlist))
The output will be:
Enter numbers 3
Enter numbers 4
Enter numbers 8
Enter numbers 2
Enter numbers 9
[3,4,8,2,9]
The smallest number is 2
My bro ,u are too much oo,u really open my eyes to many things about pythons ,which I did not know b4 .pls am a beginer to this course .I need yr help oo,to enable me know more sir.
Thanks and God bless u
Printing the items in a tuple using while loop exercise shows wrong answer please review the answer.
I just checked again, and it is the correct answer. Can you check your code once again? Maybe you might have missed something in your code.
Hi, Ashwin Thanks for these informative and variative while loops examples; they are really helpful for practicing. 🙂
Cheers.
name = input(‘name’)
strip= input(‘word’)
# Now i want to see both methods while and for to striped out the strip’s values from the name’s letters.
no output is coming in example 10.
lst = []
for i in range(5):
num = int(input(“Enter your numbers: “))
lst += [num]
print(“The greater number is”,max(lst))
print(“The smallest number is”,min(lst))
How I wish you were able to write comments on your code lines to help newbies better understand the concept.
Rony its true but what do you mean by write coments on your code
great im loving this exercises.i feel on top of the world