Python

Python Loops

Loops

There are two types of loops Python can handle, “for” and “while” loops. These loops can iterate through data, and they are vital for comprehending the programming language.

For loops

The idea behind “for” loops is to enable iterations over sequences. The keywords to execute such loops are, “for” and “in” (following the same order). Indentation is also very important.

For instance, if a list containing four items is iterated with a “for” loop, each item will list separately (one by one). The following example shows the concept of “for” loops.

# For loop with lists
list = ["Microsoft", "Apple", "IBM", "Google"]

# The "i" is optional, and it can be anything.
for i in list:
    print(i)

# The following is the same as the above.
for company in list:
    print(company)

# Output for both "for" loops
Microsoft
Apple
IBM
Google

Similar to Python conditions (if, elif, and else statements), loops require colons at the main code declaration.

python for loops example

While loops

The concept of “while” loops is to execute repeatedly statements until some condition is met. The keyword for this type of loops is “while“. Similarly to “for” loops, indentation and colons are important.

For example, in a case of counting numbers, the “while” loop executes until it reaches a pre-specified number. The following example shows the concept of “while” loops.

# While loop with variable (int)
num = 0
while num < 4:
    print(num)
    # This statement increases "num" with 1 on each iteration
    num = num + 1

# The incremental statement can also be written as "num += 1". It's a shorter version and a very common practice (explained in later tutorials).
# Output
0
1
2
3

Meeting the requirement of a “while” loop is a must. Otherwise, the loop will execute forever.

In addition, Pythonic “while” loops include the statements “break”, “continue”, and “else”. The intermediate tutorial pages of Python Fundamentals cover these three keyword statements.

python while loops example

Next: Python Input

by AICorr Team

We are proud to offer our extensive knowledge to you, for free. The AICorr Team puts a lot of effort in researching, testing, and writing the content within the platform (aicorr.com). We hope that you learn and progress forward.