codescracker


python

Python while Loop



« Previous Tutorial Next Tutorial »


Python while loop generally used to perform the same action as for loop does, but in different way. Here is the general form to use while loop in python:

while expression:
   statement(s)

Python while Loop Example

Here is an example demonstrates while loop in python:

# Python while Loop - Example Program

i=0
while(i<10):
    print(i)
    i=i+1

Here is the sample output of the above python program:

python while loop

Let's take another example program also demonstrates the use of while loop in python. This program perform the same action or the output of this program is same as the output of the program (of previous tutorial of for loop). The difference is, that program build up with for loop whereas this one with while loop:

# Python while Loop - Example Program
		
while True:
	print("Enter 'x' for exit.")
	n = input("Enter any number: ")
	if n == 'x':
		break
	else:
		val = int(n)
		nr = int(input("Upto how many rows: "))
		i = 0
		j = 0
		while i<nr:
			while j<i+1:
				print(val,end=" ")
				j = j + 1
			j = 0
			i = i + 1
			print()

Here are sample runs of the above python program of while loop. This is the first snapshot:

while loop in python

This is the second snapshot:

python while loop example

More Examples

Here are list of some more examples, uses while loop in python:


« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test