1.5. Statements#

In Python, statements are instructions that perform actions or operations. They are the fundamental building blocks of a Python program, and they define the behavior of the program. Here are some key types of statements in Python [Downey, 2015, Python Software Foundation, 2024]:

1.5.1. Assignment Statements#

Assignment statements assign values to variables using the assignment operator (=).

Example:

x = 5
name = "Alice"

Here, x is assigned the value 5, and name is assigned the string "Alice".

1.5.2. Expression Statements#

Expression statements evaluate an expression and optionally perform some action with the result.

Example:

result = 3 + 4
print(result)
7

In this example, the expression 3 + 4 is evaluated, resulting in 7, which is then printed.

1.5.3. Conditional Statements (if, elif, else)#

Conditional statements control the flow of the program based on conditions.

Remark

In Section 1.6, we will discuss conditional statements.

Example:

x = 5

if x > 10:
    print("x is greater than 10")
elif x == 10:
    print("x is equal to 10")
else:
    print("x is less than 10")
x is less than 10

Here, the condition x > 10 is false, so the else block is executed, printing x is less than 10.

1.5.4. Loop Statements (for, while)#

Loop statements execute a block of code repeatedly.

Remark

In Section 1.7, we will discuss loop statements.

Example - for loop:

for i in range(5):
    print(i)
0
1
2
3
4

This for loop iterates over a range of numbers from 0 to 4, printing each number.

Example - while loop:

x = 5

while x < 10:
    print('x =',x, ", x is still less than 10")
    x += 1
x = 5 , x is still less than 10
x = 6 , x is still less than 10
x = 7 , x is still less than 10
x = 8 , x is still less than 10
x = 9 , x is still less than 10

This while loop continues to execute as long as x is less than 10, incrementing x each time.

1.5.5. Import Statements#

Import statements import modules and functions from other files.

Remark

In Section 1.11, we will discuss import Statements.

Example:

import math
from random import randint

Here, the math module is imported, and the randint function is imported from the random module.

1.5.6. Break and Continue Statements#

Break and continue statements control the flow within loops.

Example - break:

for i in range(10):
    if i == 5:
        break  # Exit the loop when i is 5
    print(i)
0
1
2
3
4

The loop exits when i is 5.

Example - continue:

for i in range(10):
    if i % 2 == 0:
        continue  # Skip even numbers
    print(i)
1
3
5
7
9

This loop skips even numbers and prints the odd numbers.