Loops
Python - A Quick Start for existing Programers
2 min read
Published Sep 16 2025, updated Aug 17 2026
Guide Sections
Guide Comments
While loops
While loops run the indented code repeatedly while the condition is True:
# i variable as a counteri = 0# loop 5 times when i is 0,1,2,3,4while i < 5: print(i) # increment the i counter by 1 i += 1To skip to the next condition check you can use the continue statement:
i = 0while i < 5: i += 1 if i == 3: # continue back up to the chile condition check continue print(i)So this example won't print out 3 as the continue statement will take the flow back to the condition check and then increment i to 4.
To break out a while loop you can use the break statement:
i = 0while i < 5: print(i) if i == 3: # Break out of the while loop and resume executing code below it break i += 1So this example, the last number printed will be 3 and then the while loop is ended.
To run code when the while loop finishes and the condition changes to False, use the else: statement:
i = 0while i < 5: print(i) i += 1else: # This else block executes when the while loop condition becomes false # It is not executed if the loop is exited via a break statement print("Natural end of while loop")# This block executes after the while loop, even if the loop is exited via a break statementprint("After while loop")The else section will only be ran if the loop naturally gets to the end and the condition changes to False. If the while loop has a break statement ran, then the else section is skipped.
For loops
To loop through 10 iterations from 0 -> 9:
for x in range(10): print(x)To loop through 1 -> 10:
for x in range(1, 11): print(x)To loop through 2 -> 10, with a 2 step, so every other number:
for x in range(2, 11, 2): print(x)You can use the break, continue and else: statements in a for loop, in the same way you can in a while loop.
To loop through a list:
# Sample list of valuesmy_list = [10, 20, 30, 40, 50]# Iterate through the list and print each valuefor x in my_list: print(x)To loop through a list and have the elements index:
# Sample list of valuesmy_list = [10, 20, 30, 40, 50]# Iterate through the list and print each value and its indexfor i, x in enumerate(my_list): print(i, x)The first variable after the for is for the index, and the second is for the value. You need to use the enumerate function to wrap the list.