Discover The Magic Of Python Loops: For And While Loops Unveiled

Discover the Magic of Python Loops: For and While Loops Unveiled

  • Post author:
  • Post category:Python
  • Post comments:0 Comments
  • Reading time:20 mins read

Looping is a fundamental concept in programming, allowing tasks to be repeated multiple times efficiently. Python, with its intuitive syntax, offers two primary looping mechanisms: for and while loops.

The for Loop in Python

In Python, a For loop efficiently iterates over the items of a sequence, like a list or string, in the exact order they are presented.

The for loop in Python is versatile, iterating over sequences like lists, tuples, and strings.

Basic Syntax:

for items in sequence:
    # Execute this code

Iterating Over Sequences with for Loops 

Python loops can iterate over various data types, from lists to dictionaries, offering flexibility in handling data.

numbers = [1, 2, 3, 4, 5]
for num in numbers:
    print(num)
1
2
3
4
5

Iterating Over Lists

Lists are ordered collections, and iterating over them is straightforward.

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

Iterating over Tuples

Tuples are iterable objects in Python, which means you can loop through each item in a tuple using a for loop. Here’s an example to illustrate this:

# Define a tuple
fruits = ("apple", "banana", "cherry", "date", "elderberry")

# Use a for loop to iterate over the tuple
for fruit in fruits:
    print(fruit)
apple
banana
cherry
date
elderberry

Iterating Over Dictionaries

Dictionaries store key-value pairs. Use the items() method to iterate over both keys and values.

person = {"name": "John", "age": 30}
for key, value in person.items():
    print(key, value)
name John
age 30

the range() Function

The range() function generates a sequence of numbers, commonly used in loops.

for i in range(5):
    print(i)
0
1
2
3
4

Note that range(5) is not the values of 0 to 5, but the values 0 to 4.

Specifying a Start and Stop

The range() function can have a starting value specified by adding a parameter. For example, range(2, 7) generates values from 2 to 6.

for i in range(2, 7):
    print(i)
2
3
4
5
6

Using a Step Value

The range() function can increment the sequence by a specified value. For example, range(2, 10, 2) will increment by 2.

for i in range(0, 9, 2):
    print(i)
0
2
4
6
8

Negative Step Value

It is possible to count backwards for example from 5 to 1 by specifying a negative increment of -1.

for i in range(5, 0, -1):
    print(i)
5
4
3
2
1

Nested for Loops

Nested loops are loops that are contained within other loops and are particularly useful for handling multi-dimensional data.

for i in range(3):
    for j in range(3):
        print(i, j)
0 0
0 1
0 2
1 0
1 1
1 2
2 0
2 1
2 2

List Comprehensions

List comprehensions in Python offer a concise and readable way to create lists. They combine loops and conditionals into a single line, allowing for list manipulation without verbose code.

Here are some examples to illustrate their versatility:

Basic List Comprehension

Generate a list of squares for numbers from 0 to 4.

squares = [x**2 for x in range(5)]
print(squares)

Output:

[0, 1, 4, 9, 16]

Using Conditionals

In Python, list comprehensions offer a concise way to generate lists. One of its powerful features is the ability to include conditionals for filtering or modifying the data to be processed.

Generate a list of even numbers from 0 to 9.

evens = [x for x in range(10) if x % 2 == 0]
print(evens)

Output:

[0, 2, 4, 6, 8]

Nested List Comprehensions

Flatten a matrix into a single list.

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in matrix for num in row]
print(flattened)

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

Using Multiple Conditionals

Generate numbers from 0 to 9 that are either even or divisible by 3.

numbers = [x for x in range(10) if x % 2 == 0 or x % 3 == 0]
print(numbers)

Output:

[0, 2, 3, 4, 6, 8, 9]

List Comprehension with zip()


The zip() function in Python combines two or more iterables into a single iterable containing tuples. Each tuple consists of the i-th element from each of the input iterables, pairing elements based on their positions.

names = ["Alice", "Bob", "Charlie"]
scores = [85, 92, 88]
paired = [(name, score) for name, score in zip(names, scores)]
print(paired)

Output:

[('Alice', 85), ('Bob', 92), ('Charlie', 88)]

Using List Comprehension with Strings

Extract vowels from a given word.

word = "comprehension"
vowels = [letter for letter in word if letter in 'aeiou']
print(vowels)

Output:

['o', 'e', 'e', 'i', 'o']

Nested Loops in List Comprehensions

Generate coordinate pairs for x and y values from 0 to 2.

coordinates = [(x, y) for x in range(3) for y in range(3)]
print(coordinates)

Output:

[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

Enumerate Function in ‘For’ Loops

The enumerate() function in Python adds a counter to an iterable, allowing access to both index and value in a ‘for’ loop. This simplifies iteration over a sequence and enhances code readability and efficiency.

Iterating over a list and printing both the index and value.

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

Output:

   0 apple
   1 banana
   2 cherry

Using enumerate() with a Start Parameter:

Specifying a starting value for the counter.

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

Output:

   1 apple
   2 banana
   3 cherry

Enumerating Over a String:

Accessing each character in a string along with its position.

word = "hello"
for index, char in enumerate(word):
    print(index, char)

Output:

   0 h
   1 e
   2 l
   3 l
   4 o

Loop Control with the break, continue, and pass.

  • break: Exits the loop prematurely.
  • Continue: Skips to the next iteration.
  • Pass : A placeholder that does nothing, ensuring no syntax errors.
  • else: Executes when the loop concludes without encountering a break.

Break:

The break Statement Exits the loop before it completes its iterations.

for i in range(5):
  if i == 3:
    break
  print(i)
0
1
2

Continue:

The continue Statement Skips the current iteration and continues with the next.

for i in range(5):
  if i == 3:
    continue
print(i)
4

Pass:

The pass Statement is A placeholder that does nothing, ensuring no syntax errors.

for i in range(5):
  pass

The while Loop in Python

The while loop in Python executes a block of statements repeatedly, as long as a specified condition remains true. Unlike a for loop that runs for a predetermined number of times, the while loop continues until the condition set for it evaluates to False. It’s essential to ensure that the condition becomes false at some point; otherwise, the loop can run indefinitely, leading to an infinite loop.

Examples:

Basic Usage of while Loop:

Printing numbers from 1 to 5.

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

Output:

   1
   2
   3
   4
   5

Using else with while Loop:

The else block executes once the loop condition becomes false.

   count = 1
   while count <= 3:
       print(count)
       count += 1
   else:
       print("Loop finished!")

Output:

   1
   2
   3
   Loop finished!

Break Statement in while Loop:

Exiting the loop prematurely when a specific condition is met.

   count = 1
   while count <= 5:
       if count == 4:
           break
       print(count)
       count += 1

Output:

   1
   2
   3

Continue Statement in while Loop:

Skipping the current iteration and moving to the next one.

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

Output:

   1
   2
   4
   5

known in advance. However, care must be taken to avoid infinite loops by ensuring that the loop’s condition eventually becomes false.

Comparison of For and While loop

Both for and while loops are fundamental control structures in Python, allowing for repeated execution of code blocks. However, they serve slightly different purposes and are used in different scenarios. Here’s a comparison between the two:

For Loop

Purpose:

  • The for loop is used to iterate over a sequence (like a list, tuple, dictionary, set, or string) or other iterable objects.

Structure:

  • It runs for a predetermined number of times, based on the length of the sequence.

Example:

# Iterating over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

Output:

apple
banana
cherry

While Loop

Purpose:

  • The while loop is used to execute a block of statements repeatedly as long as a specified condition remains true.

Structure:

  • It’s more general than a for loop and runs until the condition set for it evaluates to False.

Example:

# Printing numbers from 1 to 3
count = 1
while count <= 3:
    print(count)
    count += 1

Output:

1
2
3

Key Differences:

  1. Initialization & Iteration:
  • In a for loop, the initialization and iteration are usually implicit (e.g., for i in range(5)).
  • In a while loop, you often need to initialize the variable before the loop and handle the iteration manually within the loop.
  1. Termination:
  • A for loop will terminate once it has iterated over the sequence.
  • A while loop requires a condition to become false to terminate. If not handled correctly, it can result in an infinite loop.
  1. Use Cases:
  • for loops are typically used when the number of iterations is known in advance (e.g., iterating over the elements of a list).
  • while loops are more suitable when the number of iterations is unknown beforehand and depends on a specific condition (e.g., reading lines from a file until there are no more lines).

In summary, while both for and while loops offer looping capabilities in Python, they cater to different needs and scenarios. Choosing between them depends on the specific requirements of the task at hand.

Every week we'll send you SAS tips and in-depth tutorials

JOIN OUR COMMUNITY OF SAS Programmers!

Subhro

Subhro provides valuable and informative content on SAS, offering a comprehensive understanding of SAS concepts. We have been creating SAS tutorials since 2019, and 9to5sas has become one of the leading free SAS resources available on the internet.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.