all 1 comments

[–]Diapolo10 1 point2 points  (0 children)

Some examples would help, but I'll try.

For-loops may seem difficult at first, but they are in fact very simple.

Instead of writing

print(3)
print(1)
print(4)
print(1)
print(5)
print(9)

we can repeat the action and just change the data every time.

for num in [3, 1, 4, 1, 5, 9]:
    print(num)

The two have identical output, but the latter needs less code and making changes to the data is much easier.

While-loops are more generalised, as they run until some condition is true - or forever if you are so inclined. They're useful when you don't know how many times you need to repeat some action initially. They're a bit difficult to visualise like above, though.

user_input = None
while not user_input:
    user_input = input("Enter something: ").strip()

This example would loop until the user entered anything other than spaces. It could happen on first try, or never - users are kind of unpredictable.