A while loop continues as long as a condition is true:
Copy
count = 0while count < 5: print(f"Count is {count}") count = count + 1 # Increase count by 1# Output:# Count is 0# Count is 1# Count is 2# Count is 3# Count is 4
Always make sure your while loop will eventually stop! If you forget to update the variable, it will run forever.
# Wrong - missing colonfor i in range(5) print(i)# Right - colon after the loop linefor i in range(5): print(i)
Wrong indentation
Copy
# Wrong - not indentedfor i in range(3):print(i)# Right - indented inside the loopfor i in range(3): print(i)
Off-by-one errors
Copy
# Wrong - only goes to 4for i in range(5): print(f"Item {i}") # 0, 1, 2, 3, 4# Right - if you want 1-5for i in range(1, 6): print(f"Item {i}") # 1, 2, 3, 4, 5