Python

Python Intermediate Loops

Python Intermediate Loops

This page covers Python intermediate loops and continues the previous tutorial of Python loops.

For Python loops here.

It continues deeper aspects of loops.

  • “continue” statement
  • “pass” statement
  • “break” statement
  • nested “for” loops

“Continue” statement

In Python, the “continue” statement stops the iteration of the loop, meaning it skips the iteration output, and then continues with the rest of the iterations. The example below can help with understanding the process.

num = [1, 2, 3]

for a in num:
    print(a)

# Output
1
2
3

Including an “if” statement with the “continue” statement. The program stops at the number 2, skips it, and then continues the rest of the iterations.

num = [1, 2, 3]

for a in num:
    if a == 2:
        continue
    print(a)

# Output
1
3

“Pass” statement

The “pass” statement works the same way as in “if” statements (previously defined). Loops cannot be empty, but the “pass” statement can resolve such issues.

num = [1, 2, 3]

for a in num:

# Output: SyntaxError
num = [1, 2, 3]

for a in num:
    pass

# Output:

“Break” statement

In Python, as the name suggests, the “break” statement stops the loop from iterating in the case of meeting a condition.

The following is an example of a “while” loop containing the statement of “break”.

a = 0

while a < 4:
    print(a)
    a += 1

# Output
0
1
2
3

Adding an “if” statement including “break”.

a = 0

while a < 4:
    print(a)
    a += 1
    if a == 2:
        break

# Output
0
1

Nested “for” loops

Similarly to nested “if” statements, nested loops encompass one loop inside another.

num = [1, 2]
countries = ["Germany", "Serbia", "France"]

for a in num:
    for b in countries:
        print(a, b)

# Output
1 Germany
1 Serbia
1 France
2 Germany
2 Serbia
2 France

In the above scenario, the nested “for” loops print the first number (1) with each element in the list of countries, and then repeats it with the second number (2).

The following is a different approach of the location of the “print” statement.

num = [1, 2]
countries = ["Germany", "Serbia", "France"]

for a in num:
    print(a)
    for b in countries:
        print(b)

# Output
1
Germany
Serbia
France
2
Germany
Serbia
France

The first element of the numbers list prints out, followed by all elements of the list of countries. The process repeats with the second number.


Next: Python Range

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.