Beginning Python programmers often don't realize just how important it is to think about indentation (i.e. how far indented your code is, by hitting the TAB key in Thonny, or typing four spaces, etc).
Indentation is how Python decides whether one statement is grouped "inside"/"outside" of a function, FOR loop, and other things.
Let's go through some examples using FOR loops, to help make this clear.
for i in range(5):
print("A")
print("B")
This code will display 5 A's, and then one B.
The print("A")
statement is "inside" the FOR loop -- that is, it runs every time the loop goes.
The print("B")
statement is "outside" -- that is, it just runs once, AFTER the loop is finished running.
Contrast this with:
for i in range(5):
print("A")
print("B")
This code will display A B A B A B A B A B (although with each letter displayed on its own line, unless we changed it to use print(...,end="")
)
This is because both print statements are "inside" the loop, so they will both get run repeatedly.
Note: you must have all your indentation line up, so if you try something like this
for i in range(5):
print("A")
print("B") #<-- bad indentation here!
then you will get an indentation error, and Python won't run your code at all, because it doesn't know whether your print statements are inside/outside, and it refuses to guess. Similarly
for i in range(5):
print("A")
print("B") #<-- bad indentation here!
this will also cause an error.
Here's one more final more complex example:
for i in range(3):
print("A", end=" ")
print("B", end=" ")
print("C", end="*")
print("D",'E','F',sep="$")
will display A B C*A B C*A B C*D$E$F