Home > Enterprise >  Python nested for loop interpretation
Python nested for loop interpretation

Time:08-10

I have this following problem from a book I’m learning from and I'd like to know how you would interpret this code to get to the answer (14) because I’m having a hard time getting there. I understand the concept of for loops but this nested one got me good:

When the looping completes, what number will display?

outer_loop_total = 0
inner_loop_total = 0
countries = ["Albania", "Morocco", "Brazil", "Denmark"]
capitals = ["Tel Aviv", "Abuja", "Brasília", "Islamabad"]
for country_to_check in countries:
  outer_loop_total  = 1
  for city_to_check in capitals:
    inner_loop_total  = 1
    if country_to_check == "Brazil" and city_to_check == "Brasília":
      print(outer_loop_total   inner_loop_total)

CodePudding user response:

The inner loop gets executed everytime the outer loop gets executed. For that outer_loop_total gets incremented until Brazil has reached. inner_loop_total gets incremented until Brasilia x times it takes to reach Brazil.

Lets calc (* 1 stands for your incremented number):

  • outer_loop_total: 3 * 1
  • inner_loop_total: ((2 * 4) 3) * 1
  • Result = outer_loop_total inner_loop_total = 3 11 = 14

Why (2 * 4) 3?

Until Morocco in countries (which is 2 times 2 * ..) it goes until Islamabad in capitals (which is 4 times .. 4).
For the last one, when it reaches Brasil in countries, it only goes until Brasília (which is 3 times -> 3) .

CodePudding user response:

Sorry now I editted. You will see 14 number as an output because you have two loops. outer_loop_total will be 3 and inner_loop_total will be 11. You have 4 countries in your countries list. Your outer for loop will iterate in countries list orderly. For each country iterated , you iterate in all capitals in capital list. When your current country is "Brazil" and when your current capital is "Brasilia" you will see the output.

  • Related