How to use multiple for and while loops together in Python?


You can create nested loops in python fairly easily. You can even nest a for loop inside a while loop or the other way around. For example,

for i in range(5):
   j = i
   while j != 0:
      print(j, end=', ')
      j -= 1
   print("")

This will give the output

1,
2, 1,
3, 2, 1,
4, 3, 2, 1,

You can take this nesting to as many levels as you like.

Updated on: 17-Jun-2020

228 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements