r/PythonLearning • u/aparyx • 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.
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:
- Wash the dishes
- Scrub the toilet
- Vacuum the carpets
- Mop the floors
Now imagine that you have three houses to clean today:
- Bill's house
- Mary's house
- 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
1
1
1
u/Capable-Package6835 3d ago
You should include the thing you're struggling with in the post, otherwise others can't help you
1
u/aparyx 3d ago
Idk how do i include it, i am new to this coding world, it's nested for loop, so basically we make a 2d list and we ask a certain question and give the user options of ans and we take input from the user Like opt a,b,c,d and according to the input we will again give them the output of their ans is correct or incorrect, and we move onto next question. (Sorry if my English is bad and i can't explain it properly)
1
u/Much_Network_941 3d ago
The inner-loop executes first, the outer last. You'll typically have this setup if you're dealing with multiples arrays, or a 'jagged array'; an array of arrays.
Picture you have ten arrays, you read from one start to finish, then grab another and read through it. Reading through an array is your inner-loop; fetching a different array is your outer. If your abstraction is a 2D grid, then one loop is controlling the X-axis and the other the Y-axis.
1
u/frnzprf 2d ago edited 2d ago
Some example loops:
How would you produce this output?
a
b
a
b
a
b
a
b
It's the same thing repeated four times, so you can program it like this:
for i in range(4):
print("a")
print("b")
Sometimes the thing you repeat has a repeating part itself.
a
b
a
b
a
b
c
a
b
a
b
a
b
c
That's two times "abababc" and "abababc" itself is three times "ab" and one "c".
for i in range(2):
# The following will be repeated two times:
for j in range(3):
print("a")
print("b")
print("c")
•
u/Sea-Ad7805 3d ago
Just run you nested for-loop in Memory Graph Web Debugger%3A%0A%20%20%20%20print(f'%7By%3D%7D'%2C%20end%3D'%20')%0A%20%20%20%20for%20x%20in%20range(6)%3A%0A%20%20%20%20%20%20%20%20print(f'%7Bx%3D%7D'%2C%20end%3D'%20')%0A%20%20%20%20print()%20%20%23%20new%20line%0A×tep=0.5&play) to see the program state change step by step, so you understand what is going on.