Statements in Python are instructions that the interpreter executes. They are the building blocks of a Python program, enabling it to perform specific tasks like calculations, decision-making, or looping.

Below is a description of the primary types of statements in Python:

1. Expression Statements

  • An expression statement evaluates an expression and optionally assigns the result to a variable.

  • These are typically used for calculations, assignments, or calling functions.

x = 10 + 5  # Assignment statement
print(x)    # Function call
    
2. Conditional Statements
  • These allow decision-making in the program by executing code blocks based on conditions.

  • Keywords: if, elif, else.

age = 18
if age >= 18:
    print("You are an adult.")
elif age > 12:
    print("You are a teenager.")
else:
    print("You are a child.)
3. Looping Statements
  • Used to repeat a block of code multiple times.

  • Keywords: for, while.

3.1 For Loop :

The for loop in Python is a control flow statement used to iterate over a sequence (such as a list, tuple, dictionary, string, or range) and execute a block of code for each item in that sequence.

Unlike traditional C-style for loops that rely on incrementing/decrementing counters, Python’s for loop directly iterates over the elements of the sequence.

Below is the “for” loop example :

List =[0,1,2,3,4,5,6,7,8,9,10]
# For loop
For i in list : 
	Print(i)
#O/P : 0,1,2,3,4,5,6,7,8,9,10

For i in list[4:10] : #here 4 is inclusive and 10 is exclusive
	Print(i)
#O/P : 4,5,6,7,8,9

We can implement for loop using range() function as well. It’s a built-in function used to generate a sequence of numbers. It is commonly used in loops to iterate over a fixed sequence of numbers.

range(start, stop, step)

  • start (optional): The starting value of the sequence. Default is 0.
  • stop (required): The ending value of the sequence (exclusive).
  • step (optional): The difference between each number in the sequence. Default is 1.

Below is the “for” loop example by using range() function :

# For loop
For i in range(11) : 
	Print(i)
#O/P : 0,1,2,3,4,5,6,7,8,9,10 It generated 11 numbers starting from zero

For i in range(4,11) : #here 4 is inclusive and 11 is exclusive
	Print(i)
#O/P : 4,5,6,7,8,9,10

For i in range(4,11,2) : #here 4 is inclusive, 11 is exclusive and increment numbers by 2
	Print(i)
#O/P : 4,6,8,10

3.2 While Loop :

The while loop in Python is a control flow statement that repeatedly executes a block of code as long as a specified condition evaluates to True. It is typically used when the number of iterations is not known beforehand and depends on a condition.

Below is the “While” loop example :

# While loop
count = 0
while count <= 10:
    print(count)
    count += 1
#O/P : 0,1,2,3,4,5,6,7,8,9,10
    

Below is the example of iterating over different Data Types :

# From Tuple
colors = ("red", "green", "blue")
for color in colors:
    print(color)
    
#From Dictionary
data = {"name": "Alice", "age": 25}
for key in data:
    print(key)

for key, value in data.items():
    print(f"{key}: {value}")

#From Matrix
matrix = [[1, 2], [3, 4], [5, 6]]
for row in matrix:
    for num in row:
        print(num, end=" ")
    
4. Break and Continue Statements
  • break: It terminates the loop entirely and moves to outside of loop.
  • continue: It skips the current iteration and moves to the next iteration of the loop.

        Below is the “Break” and “Continue” example :

# use of break statement
for i in range(5):
    if i == 3:
        break  # Exit the loop
    print(i)

# use of continue statement
for i in range(5):
    if i == 3:
        continue  # Skip this iteration
    print(i)
5. Function Definition Statements
  • It define reusable blocks of code, which can be called with specific inputs.

  • Keyword: def.

        Below is the example :

def greet(name):
    return f"Hello, {name}!"
print(greet("Alice"))
6. Import Statements
  • Used to include external modules and libraries in the program.

  • Keywords: import, from.

        Below is the example :

import math
print(math.sqrt(16))

from datetime import datetime
print(datetime.now())
7. Pass Statement
  • A placeholder that does nothing and allows the program to run without error when a statement is syntactically required but has no content.

        Below is the example :

def my_function():
    pass  # Placeholder for future code
8. Return Statement
  • Used to exit a function and optionally send a value back to the caller.

  • Keyword: return.

        Below is the example :

def square(x):
    return x * x
print(square(4))  # Output: 16
9. Assert Statement
  • Used to debug by checking conditions during program execution. If the condition is False, an AssertionError is raised.

  • Keyword: assert.

        Below is the example :

x = 5
assert x > 0, "x must be positive"
10. Del Statement
  • Deletes variables or elements from collections.

  • Keyword: del.

        Below is the example :

my_list = [1, 2, 3]
del my_list[1]
print(my_list)  # Output: [1, 3]
11. Global and Nonlocal Statements
  • Used to declare the scope of variables.

    • global: Declares a variable as global.
    • nonlocal: Declares a variable in the nearest enclosing (non-global) scope.

        Below is the example :

# Global example
global_var = 10

def change_global():
    global global_var
    global_var = 20

# Nonlocal example
def outer():
    x = 10
    def inner():
        nonlocal x
        x = 20
    inner()
    print(x)  # Output: 20