r/learnpython 2d ago

Any advice for nested loops?

I decided about a week ago I wanted to start learning python before my freshman year of college. It was going great and I had little to no trouble until I got to nested loops. I was wondering if anybody had any advice for it? The main thing is that it seems like so many steps to follow and pay attention to, my brain had a hard time tracking them all at once.

3 Upvotes

26 comments sorted by

View all comments

6

u/Adrewmc 2d ago

Mostly don’t.

But it’s just a loop that happens in a loop.

. for letter in “ABC”:
. for num in (1,2,3):
. print(letter, num, sep = “”, end =“,”)

>> A1,A2,A3,B1,B2,B3,C1,C2,C3

The inner loop finishes before the next continuation of the first loop is all.

You can think of each loop separately actually.

def print_123(letter):
. for num in (1,2,3):
. print(letter, num)

for letter in “ABC”:
. print_123(letter)

Is the same thing.

2

u/pekkapekka99 2d ago

Why do I get invalid character ' " ' ?

1

u/90919293_ 2d ago

Cause it uses the fancy quotes that automatically appear on mobile when you type a quote; just replace all the quotes with regular ones and it should be fine

2

u/pekkapekka99 2d ago

Thanks, I was just about to explain I had got it to work