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.
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': break else: 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=" ") print()
Here is the sample run of the above python program:
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.
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: statement(s) statement(s)
Here is the syntax to use nested while loop in python:
while expression: while expression: statement(s) statement(s)
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:
Here are list of some more examples uses loops in python: