Learn Python in 7 days: Day 4 - Loops-for & while

Shashank Shetty
Shashank Shetty

Comment section

You need to be a subscriber to comment


Loops - for & while

List of contents:

  1. For loop
  2. While loop
  3. More to know

One of the major advantages of computers is that they can perform boring actions many many times and with consistent results. In Python, to perform actions repeatedly, you can use Loops. As the name suggests, they loop through a block of code based on certain conditions. There are two main types of loops in Python: for loop and while loop

For loop

A for loop is a loop that repeats "for" a fixed number of times. That number is based on an iterable item that is passed to the loop. An iterable is simply a type of object that can iterated through, or looped through. Think, a list; you can loop through every element in the list. A list is an iterable, so is a string and a tuple and a set. The syntax declares a dynamic variable which changes for each loop. Here is an example:


fruits: list = ['Apple', 'Banana', 'Cherry', 'Durian']

# A for loop that iterates through the list fruits.
# The word after the keyword for is the variable that will change for each loop.
for fruit in fruits:
    print(f"{fruit} is yummy!")
        

Note that loops too follow the classic indentation in Python. In this loop, the for loop iterates through the list of fruits, and for each iteration, the variable fruit is changed into one of the elements in the list. The loop will run for a fixed number of times, i.e., the number of elements in the iterable, in this case, the list. Surprisingly, a number is not an iterable. This will not work: for num in 10:. To use a number in a for loop, we can make use of the range function which creates an iterator (a bit complicated, just know the word for now).


for i in range(10):
    print(i)
# The counting starts from 0. It prints 10 numbers, but not 10 itself as it starts from 0. So the number given is excluded

for i in range(1, 11):
    print(i)
# You can also give the starting number to the range() function. Since 11 is excluded, it prints 1 to 10.

for i in range(2, 11, 2):
    print(i)
# The range function also takes a step as an input. It is just the number of steps to take after each iteration.
# Starting from 2, it prints every second number until 10; the even numbers.
        

Another cool iterable is a dictionary. For this, two dynamic variables are declared, one for the key and one for the value.


insects: dict = {'A': 'Ant', 'B': 'Beetle', 'C': 'Cicada', 'D': 'Dragonfly'}

for alphabet, insect in insects.items():
    print(f"{alphabet} is for {insect}")

# The items() method is actually converting the dictionary into a list of tuples. The above dictionary becomes:
#   [('A', 'Ant'), ('B', 'Beetle'), ('C', 'Cicada'), ('D', 'Dragonfly')]
# Meaning, you can have any number of dynamic variables, as long as the number of variables is equal to the number of elements in the iterables in the iterable.

candidates: list[tuple] = [('Aarav', 26, 'Tamil Nadu'), ('Bilal', 30, 'Uttar Pradesh'), ('Chaitanya', 28, 'Assam')]

for name, age, state in candidates:
    print(f"{name} is {age} years old and is from {state}.")
        

It is not necessary that a for loop should finish all its iterations. You can manually break a loop with the, break keyword. Another useful keyword is the continue keyword that skips the current iteration, meaning it just prevents the following code from being executed for that ONE loop and then continue with the next iteration.


party_popper: str = "Yusuf"

guests: list = ["Waseem", "Xavier", "Yusuf", "Zayan"]
for guest in guests:
    if guest == party_popper:
        print(f"{guest} is a party popper!")
        break
    print(f"Welcome to the party {guest}!")

# We do not have to specify an else statement because the code after the if condition will run if it evaluates to False.
# If it evaluates to True, the program will not reach the welcome text because it breaks out of the loop.

owner: str = "Rachel"

customers: list = ["Peretz", "Qasim", "Rachel", "Suresh"]
for customer in customers:
    if customer == owner:
        print("Good day boss!")
        continue
    print(f"Hmm, let me check. That will be 85 Rs., {customer}.")

# Even though the last print statement is not locked behind any conditional statement,
# it will not be executed for the owner, because that loop is skipped
        

While loop

A while loop is a loop that repeats as long as or "while" something is True. That something is again an operator that returns True or False. It must be taken care that you don't create an unintentional infinite loop by passing a condition that will always return True. It will not terminate till the program is externally stopped.


i: int = 0

while i < 10:
    print(i)
    i += 1

# At the end of each loop, one is added to the counting variable i so that at some point, i < 10 will be false.
        

The while loop can also make use of the break and continue keywords.


i: int = 0

while True:
    if i == 11:
        break
    print(i)
    i += 1

# We can safely create an infinite loop because we are breaking out of it when i == 11.

j: int = 1

while j <= 10:
    if j % 2 == 0:
        j += 1
        continue
    print(j)
    j += 1
# The continue keyword is used to skip the even numbers.
        

More to know

  • You can nest loops; meaning you can place loops within loops. Here is an example that creates all possible 2-digit binary numbers:
  • 
    for i in [0, 1]:
        for j in [0, 1]:
            print(i,j)
    # For every digit in [0, 1], it prints it with every digit in [0, 1].
    # Nesting more loops creates more digits. Increasing list size changes the base from binary to ternary to quaternary, etc.
                
  • If you do not care about the index/number of the current iteration in a for loop, or you don't use the variable in the loop but just do an action for a number of times, you can use an underscore _ instead of a variable to make it a tad bit more efficient, but you can't access it like a variable.
  • Astonishingly, loops can also have else statements. The block under the else statement is executed only if the loop finishes completely. If the loop is broken by a break keyword, the else block will not be run. So, if you want to know whether a loop ended because it looped through all the elements or because it was stopped by a break trigger, you can use it.