Python: Nested Loop


A loop within a loop is known as nested loop.

Assume that there are 5 passengers and each of them have 2 baggage. The below code will make sure that all baggage of each passenger have undergone the security check.

Example

num_of_pasngrs=5
num_of_bag=2
security_check=True
for pasngr_count in range(1, num_of_pasngrs+1):
	  for bag_count in range(1,num_of_bag+1):
	      if(security_check==True):
	          print("Security check of passenger:", pasngr_count, "-- baggage:", bag_count,"baggage cleared")
	      else:
	          print("Security check of passenger:", pasngr_count, "-- baggage:", bag_count,"baggage not cleared")

Output

Security check of passenger: 1 — baggage: 1 baggage cleared
Security check of passenger: 1 — baggage: 2 baggage cleared
Security check of passenger: 2 — baggage: 1 baggage cleared
Security check of passenger: 2 — baggage: 2 baggage cleared
Security check of passenger: 3 — baggage: 1 baggage cleared
Security check of passenger: 3 — baggage: 2 baggage cleared
Security check of passenger: 4 — baggage: 1 baggage cleared
Security check of passenger: 4 — baggage: 2 baggage cleared
Security check of passenger: 5 — baggage: 1 baggage cleared
Security check of passenger: 5 — baggage: 2 baggage cleared

The same code in the inner loop can also be written using while loop instead of for loop as shown below:

num_of_pasngrs=5
num_of_bag=2
security_check=True
for pasngr_count in range(1, number_of_passengers+1):
	bag_count =1
	while (bag_count<=num_of_bag):
	   if(security_check==True):
	      print("Security check of passenger:", pasngr_count, "-- baggage:", bag_count,"baggage cleared")
	   else:
	      print("Security check of passenger:", pasngr_count, "-- baggage:", bag_count,"baggage not cleared")
	   bag_count+=1	 

Similarly, the outer loop can also be written using while loop.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s