Statements

This part will cover the following topics:

  • loop statements

    • for loop

    • while loop

  • conditional statements

    • if, elif, and else statements

  • break and continue statements

    • break

    • continue

  • assert statement

    • assert

Loop statements

for loop

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

sequence = [1, 2, 3, 4, 5]
for element in sequence:
    print(element)

range() function is normally used with the for loop to iterate over a sequence of numbers.

print(list(range(5)))
# range(stop)
print('range(5):')
for i in range(5):
    print(i)

# range(start, stop)
print('range(1, 5):')
for i in range(1, 5):
    print(i)

# range(start, stop, step)
print('range(1, 10, 2):')
for i in range(1, 10, 2):
    print(i)

while loop

The while loop is used to execute a block of code as long as the condition is true.

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

To create an infinite loop, you can use while True.

while True:
    print("Infinite loop")

hint: To stop the infinite loop, press Ctrl + C (Windows) or Cmd + C (Mac).

Conditional statements

if, elif, and else statements

The if statement is used to execute a block of code if the condition is true.

x = 10
if x > 5:
    print("x is greater than 5")

The elif statement is used to check multiple expressions for True and execute a block of code as soon as one of the conditions is true.

x = 10
if x > 5:
    print("x is greater than 5")
elif x < 5:
    print("x is less than 5")

The else statement is used to execute a block of code if the condition is false.

x = 10
if x > 5:
    print("x is greater than 5")
else:
    print("x is less than 5")

Q: What is the difference between elif and else?

Break and continue statements

break

The break statement is used to exit the loop.

sequence = [1, 2, 3, 4, 5]
for element in sequence:
    if element == 3:
        break
    print(element)

In this example, the loop will stop when the element is equal to 3.

continue

The continue statement is used to skip the current iteration and continue with the next iteration.

sequence = [1, 2, 3, 4, 5]
for element in sequence:
    if element == 3:
        continue
    print(element)

In this example, when the element is equal to 3, the loop will skip the current iteration and continue with the next iteration.

Assert statement

The assert statement is used to check if the condition is True. If the condition is False, the program will raise an AssertionError. The assert statement is used for debugging code.

score = 58
assert score > 60, "failed, score is less than 60"

In this example, the program will raise an AssertionError because the score is less than 60. The message will be displayed as follows:

AssertionError: failed, score is less than 60

Last updated