for x in range(5):
print(x)
0
1
2
3
4
Here is a statement which is outside the loop because there is no indenting at the beginning of the line
for x in range(5):
print(x)
print("I am outside the loop")
Output is here .
0
1
2
3
4
I am outside the loop
In the above code the range is from 0 to 5 ( excluding 5 ) , so we get output from 0 to 4.
for x in range(5,10):
print(x)
Output is here
5
6
7
8
9
We can add a increment value
for x in range(5,25,5):
print(x)
Output is here
5
10
15
20
for x in range(5,25,5):
if(x==15):
continue
print(x)
5
10
20
Using break
for x in range(5,25,5):
if(x==15):
break
print(x)
5
10
for x in range(5,25,5):
if(x==15):
continue
print(x)
else:
print("Out of loop but with else")
print("Out of loop")
Output is here
5
10
20
Out of loop but with else
Out of loop
Code block inside else will be executed in case of continue but not executed in case of break. for x in range(5,25,5):
if(x==15):
break
print(x)
else:
print("Out of loop but with else")
print("Out of loop")
Output is here ( else part is skipped )
5
10
Out of loop
Check how else in for loop is used to display all prime numbers upto 100.
num=100 # change this value to get all prime numbers
for i in range(2,num-1):
for j in range(2,i-1):
if (i%j == 0):
break
else:
print( i," is a prime number")
Output is
2 is a prime number
3 is a prime number
5 is a prime number
7 is a prime number
-----
-----
83 is a prime number
89 is a prime number
97 is a prime number
names=["King","Queen","Jack & others"]
for str1 in names:
print(str1)
Output is here
King
Queen
Jack & others
for i in range(5):
for j in range(5):
print('*',end='')
print("")
Output is here
*****
*****
*****
*****
*****
More on Patterns using nested for loops Multiplication table using nested for loops
names=["King","Queen","Jack & others"]
ages=["child","Young","old"]
for str1 in names:
for str2 in ages:
print(str1,str2)
Output is here
King child
King Young
King old
Queen child
Queen Young
Queen old
Jack & others child
Jack & others Young
Jack & others old
Author
🎥 Join me live on YouTubePassionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.