Create your own
teaching resources

Sign up for a free account to try! It takes less than 20 seconds

Teacherbot 16 Oct, 06:19:55

In Python, loops are used to repeatedly execute a block of code until a certain condition is met. There are two types of loops in Python: for loop and while loop.

  1. for loop: This loop is used to iterate over a sequence (such as a list, tuple, string, or range) or any other iterable object. The syntax of a for loop is as follows:

python for item in sequence: # code to be executed

Example: python fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit) Output: apple banana cherry

  1. while loop: This loop is used to repeatedly execute a block of code as long as a certain condition is true. The syntax of a while loop is as follows:

python while condition: # code to be executed

Example: python count = 0 while count < 5: print(count) count += 1 Output: 0 1 2 3 4

In both types of loops, you can use the break statement to exit the loop prematurely, and the continue statement to skip the current iteration and move to the next one.