Python – Part #3 (While & For Loops)

What is a loop and why do we use it?

A loop is a repetition of a process that is iterated over and over as long as the condition is true or until it is intentionally broken.

It is highly useful because it massively reduces the repetition of the code and increases its efficiency.

Note: The hash ” # ” represents the comments which do not alter the code.

WHILE LOOPS:

Example:

x = 1 # Variable declaration

while x <= 5:

    print(x)

    x += 1

Because 1 is less than 5, my boolean condition is true, or in other words: as long as 1 is less than 5 run the program, however, I am adding one to the number each time the program is repeated, so it will automatically stop as soon as the boolean condition is not true anymore.

Output:

            >> 1

            >> 2

            >> 3

            >> 4

            >> 5

FOR LOOPS:

Used to iterate over a sequence usually of lists, strings and ranges.

Example #1:

languages = [“Python”, “Java”, “C”]

for x in languages:

    print(x)

Output:

            >> Python

            >> Java

            >> C

Example #2:

The following program will take the item_prices’ list numbers and add them up to get the total price.

item_prices = [10,20,30]

total = 0    #This variable is set to 0 to add up all prices in the list.

for price in item_prices:

    total += price

print(f”The total price of your purchases is ${total}”)

Output:

            >> The total price of your purchases is $60