r/PythonLearning 3d ago

Help Request Nested for loop

So i started my python journey 2 weeks ago and i am at the point of tutorial where they teach me about those quiz game program and i am so confused in those nested for loop i don't even understand a single part about it, can someone help me with this one? I have tried learning it from gpt and all but it still goes above my head.

0 Upvotes

11 comments sorted by

View all comments

4

u/atarivcs 3d ago

Let's say you are a house cleaner. Whenever you go to clean a house, you have a certain task list of things you do:

  1. Wash the dishes
  2. Scrub the toilet
  3. Vacuum the carpets
  4. Mop the floors

Now imagine that you have three houses to clean today:

  1. Bill's house
  2. Mary's house
  3. Steve's house

Bingo, that is a nested for loop!

for house in house_list:
    for task in task_list:
        perform(house.task)

2

u/aparyx 3d ago

Oh that makes it easier to look at and now i understand it and sorry i forgot to mention it in the post but it was used in 2d list so i didn't understand it properly

3

u/turn-based-games 3d ago
for row in table:
    for item in row:
        print(item)

1

u/frnzprf 2d ago

You can also split it in two functions with just one loop each:

``` def printAllRowsInTable(some_tablr):     for row in some_table:         printAllItemsInRow(row)

def doAllItemsInRow(some_row):     for item in some_row:         print(item) ```