w1coding.comAll tutorials

Python Loops

Python lessons
  1. Environment Setup
  2. Introduction
  3. Control
  4. Control
  5. Loops
  6. Functions
  7. Lists
  8. Dictionary
  9. Classes
  10. Exception
  11. File
  12. Libray
  13. Date
  14. Regula
  15. JSON
  16. Web
  17. Zweb
  18. Apis
  19. Unity
  20. Llampda
  21. Iterators
  22. Generators
  23. Files
  24. Context
  25. Ilogging
  26. Multithreading
  27. Networking
  28. SQLite

Python Loops (For and While Loops)

Loops allow you to execute a block of code multiple times. Python supports both for and while loops.

For Loop

The for loop is used to iterate over a sequence (such as a list, tuple, or string):

      
        for i in range(5):
            print(i)
      
    

This will print the numbers 0 through 4.

While Loop

The while loop runs as long as a condition is True:

      
        count = 0
        while count < 5:
            print(count)
            count += 1
      
    

This will also print the numbers 0 through 4.

Activity

Try It Yourself!

Create a loop that prints all even numbers from 0 to 20.

Quick Quiz

Quick Quiz

  1. What is the difference between a for loop and a while loop?
  2. How do you stop a loop early in Python?

Answers: A for loop iterates over a sequence, while a while loop runs as long as a condition is True. Use break to stop a loop early.