Python Loops

« Previous Tutorial Next Tutorial »

Loops in Python are used to control your program. Loops are basically used to execute a block of code several number of times accordingly. There are the following types of loops available in Python:

You will learn about for and while loop in separate tutorial.

Python Loop Example Program

Here is an example illustrating loops in python:

# Python Loops - Example Program
while True:
	print("Enter 'x' for exit.")
	val = input("Enter any number: ")
	if val == 'x':
		num = int(val)
		nrow = int(input("Upto how many rows: "))
		for i in range(0, nrow):
			for j in range(0, i+1):
				print(num,end=" ")

Here is the sample run of the above python program:

python loops

As you can see from the above python program, both for and while loops are used. Now let's take a look at nested loop in python.

Python nested Loop

You are free to use one loop inside another loop in python. Here is the general form to use nested for loop in python:

for iterating-var in sequence:
	for iterating-var in sequence:

Here is the syntax to use nested while loop in python:

while expression:
   while expression:


Here is an example, demonstrates the concept and use of nested loop in python:

# Python Loops - Python nested Loop - Example Program

for i in range(10):
    for j in range(2):
        print(i, "\t", j)

Here is the output produced by the above Python program:

python nested loop

More Examples

Here are list of some more examples uses loops in python:

« Previous Tutorial Next Tutorial »

Latest 5 Posts by CodesCracker


Quick Links
Signup - Login - Give Online Test