How to Create a Loop in Python?

Estimated read time 2 min read

To create a loop in Python, you can use either a for loop or a while loop. Here are a few examples of how to create loops in Python:

Example 1: Using a for loop to iterate over a range of numbers

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

In this example, we use a for loop with the range() function to loop over the numbers 0 to 4. The loop iterates 5 times, and for each iteration, the value of i is printed to the console.

Example 2: Using a for loop to iterate over a list of strings

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

In this example, we define a list of strings called fruits. We then use a for loop to loop over each string in the list, and print each string to the console.

Example 3: Using a while loop to loop until a condition is met

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

In this example, we define a variable i with an initial value of 0. We then use a while loop to loop until i is greater than or equal to 5. For each iteration of the loop, we print the value of i to the console, and then increment i by 1 using the += operator.

You can modify these examples to loop over different ranges of numbers or to use different conditions to stop the loop.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply