Types of loop in Python

Mars 147 Published: 06/21/2024

Types of loop in Python

I'll respond in English as you requested.

There are several types of loops in Python, each serving a specific purpose and having its own unique characteristics.

For Loop: A for loop is used to iterate over a sequence (like a list or tuple) or other iterable objects. It's useful when you need to repeat an action for each item in the sequence. The basic syntax is:
    for variable in sequence:

do something

For example, if you have a list of numbers and want to print each number on a new line:

    numbers = [1, 2, 3, 4, 5]

for num in numbers:

print(num)

While Loop: A while loop continues to execute as long as the given condition is true. It's useful when you need to repeat an action until a certain condition is met. The basic syntax is:
    while condition:

do something

For example, if you want to keep asking for the user's name until they type "exit":

    name = input("Enter your name: ")

while name != "exit":

print(f"Hello, {name}!")

name = input("Enter your name: ")

Nested Loops: Nested loops allow you to iterate over multiple sequences simultaneously. The basic syntax is:
    for outer_variable in outer_sequence:

for inner_variable in inner_sequence:

do something

For example, if you have two lists of numbers and want to print each pair on a new line:

    list1 = [1, 2, 3]

list2 = ["a", "b", "c"]

for num1 in list1:

for letter in list2:

print(f"{num1}, {letter}")

Loop Control Statements: Python has several statements that can be used to control the flow of a loop: break: Terminates the current loop and continues executing the next line. continue: Skips to the next iteration of the loop, ignoring any remaining code within the current iteration. pass: Does nothing but is useful as a placeholder or in situations where you want to do nothing.

Here's an example of using break:

    for i in range(5):

if i == 3:

break

print(i)

In conclusion, loops are essential in Python and can be used in a wide variety of scenarios. Understanding the different types of loops and how to use them effectively will help you write more efficient and concise code.

Python for loop range

I can't help you with that. If you want to write a script in python that loops over a range of numbers, here's an example:

for i in range(1,10): # This is the most common usage.

print(i)

Now let's try some variations Start from 0 and end at 5

for j in range(6):

print(j)

Start from -2 and end at 3

for k in range(-2,4):

print(k)

Start from 1 and go to infinity (well, not really, but it's close)

for l in itertools.count(1): # Don't forget about itertools

if l > 10000: break # I mean, you can't make them go forever...

print(l)

Start at some number and increment by some other number

for m in range(5,20,3): # Increment by 3 each time

print(m)

I hope this helps.