DEV Community

Lameck Odhiambo
Lameck Odhiambo

Posted on

Python Loops

Introduction

  • Loops control the flow of a code, repeats a block of code until a condition is met.
  • In Python, loops are used to repeatedly execute a block of code. Python provides two main types of loops: for loops and while loops

Iterables : An object/collection that can return its elements one at a time allowing it to be iterated in a loop.

For loops

  • A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
  • Goes through a list of item one by one, to do something for each item.
fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x)
Enter fullscreen mode Exit fullscreen mode

Output:

apple
banana
cherry
Enter fullscreen mode Exit fullscreen mode
  • For loop ends immediately it reaches the last item in the collection; for example in this case, when it reached cherry - the last item, it automatically ends the loop.

Looping Through a String

  • Even strings are iterable objects, they contain a sequence of characters.
for x in "banana":
  print(x)
Enter fullscreen mode Exit fullscreen mode

Output

b
a
n
a
n
a
Enter fullscreen mode Exit fullscreen mode

Python Looping Through a Range

  • To loop through a set of code a specified number of times, we can use the range() function, The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.
for x in range(6):
  print(x)
Enter fullscreen mode Exit fullscreen mode

Output:

0
1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode
  • The range() function defaults to 0 as a starting value, however it is possible to specify the starting value by adding a parameter: range(2, 6), which means values from 2 to 6 (but not including 6)

  • The range() function defaults to increment the sequence by 1, however it is possible to specify the increment value by adding a third parameter: range(2, 30, 3)

Break statement

  • With the break statement we can stop the loop before it has looped through all the items, if a condition is met.
fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x)
  if x == "banana":
    break
Enter fullscreen mode Exit fullscreen mode
  • Once a condition is met in the loop, then it will stop at that condition and will not loop over the remaining items in the iterable.
  • In this case it will stop at the banana and will not loop upto the cherry.

Output:

apple
banana
Enter fullscreen mode Exit fullscreen mode

Continue statement

  • Continue statement is used to skip an item in an iterable when it matches the condition given and continue on to loop over the others.
fruits = ["apple", "banana", "cherry"]
for x in fruits:
  if x == "banana":
    continue
  print(x)
Enter fullscreen mode Exit fullscreen mode
  • In this case it will print all items in the iterable but banana.

Output:

apple
cherry
Enter fullscreen mode Exit fullscreen mode

Nested Loops

  • A nested loop is a loop inside a loop.
  • For every outer loop print all the inner loop. The "inner loop" will be executed one time for each iteration of the "outer loop".
  • Round one of the outer loop prints all items in the inner loop.
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]

for x in adj:
  for y in fruits:
    print(x, y)
Enter fullscreen mode Exit fullscreen mode

Output:

red apple
red banana
red cherry
big apple
big banana
big cherry
tasty apple
tasty banana
tasty cherry
Enter fullscreen mode Exit fullscreen mode

While Loops

  • With the while loop we can execute a set of statements as long as a condition is true.
  • Break and continue statements can also be used here.

While Condition

i = 1
while i < 6:
  print(i)
  i += 1
Enter fullscreen mode Exit fullscreen mode

output:

1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode
  • The loop will continue as long as its i is under 6 is True but when it becomes greater than 6 it becomes False and hence breaks the loop and stops.

While True

  • It creates an infinite loop, meaning the code inside it will repeat indefinitely because the condition is permanently set to True.To stop a while True: loop, you must explicitly exit it from the inside—usually by using a break statement when a certain condition is met.

Common Use Cases

  1. Validating User Input: Keep asking the user for data until they provide a valid response.

  2. Game Loops or Event Listeners: Keep a program running continuously to listen for user actions, network data, or events.

  3. Emulating a "Do-While" Loop: Forcing a block of code to run at least once before checking an exit condition

while True:
    user_input = input("Type 'exit' to stop the loop: ")

    if user_input.lower() == 'exit':
        print("Exiting the loop...")
        break  # Immediately exits the loop

    print(f"You typed: {user_input}")
Enter fullscreen mode Exit fullscreen mode
  • If you forget to include a break statement (or if your if condition can never be met), the loop will run forever and lock up your program.
  • You can stop it by pressing Ctrl + C to force-kill the program.

Difference between while condition and while true

  • While condition exits normaly when the condition is false, while true must have if and break statements
  • While condition is safer and more readable, while true has risks of infinite loop and is more flexible
  • While condition is used in counters and retries, while true is used when getting response from databases, APIs or stream

Difference between for loops and while loops

  • For loops loop over a fixed sequence, while loops loop while the condition is true
  • For loops uses predefined condition, while loops uses your condition
  • For loops number of iteration is known, while loop number of iteration is unknown

Conclusion

Loops in Python are essential control flow structures that allow you to execute a block of code repeatedly, eliminating the need for redundant code and making programs more efficient. Python primarily relies on two types of loops: for loops (for iterating over a known sequence or iterable) and while loops (for repeating code as long as a specific condition remains true).

Top comments (0)