Python Statements
Comprehensive Guide to Python Statements
In Python, statements are the building blocks of programs. A statement is a single line of code that performs a specific action. Python statements can be broadly categorized into simple and compound statements. In this blog, we’ll explore all types of Python statements with examples and explanations, from basic operations to advanced techniques.
❉ Simple Statements
Simple statements are the most basic form of instructions in Python. They typically occupy a single line and perform a single action.
1. Expression Statement
An expression statement evaluates an expression and prints its value if in an interactive session. These are typically used to assign values or perform computations.
# Expression statements
x = 5 + 3
print(x) # Output: 8
2. Assignment Statement
Assignment statements assign values to variables using the =
operator. Python supports multiple assignment styles.
# Basic assignment
a = 10
# Multiple assignment
x, y, z = 1, 2, 3
# Chained assignment
m = n = p = 5
3. Augmented Assignment Statement
This type of statement combines an operation with an assignment.
x = 10
x += 5 # Same as x = x + 5
print(x) # Output: 15
❉ Compound Statements
Compound statements are more complex and may span multiple lines. They control the flow of the program and include keywords such as if
, while
, for
, try
, and def
.
1. if Statement
The if
statement is used for decision-making. It evaluates a condition and executes the associated block if the condition is True
.
x = 10
if x > 5:
print("x is greater than 5")
elif x == 5:
print("x is equal to 5")
else:
print("x is less than 5")
2. for Loop
The for
loop iterates over a sequence (like a list, tuple, or string).
for i in range(5):
print(i) # Prints numbers from 0 to 4
3. while Loop
The while
loop continues as long as a condition is True
.
n = 5
while n > 0:
print(n)
n -= 1
4. break Statement
The break
statement terminates the nearest enclosing loop.
for i in range(5):
if i == 3:
break
print(i)
5. continue Statement
The continue
statement skips the rest of the loop’s body for the current iteration.
for i in range(5):
if i == 3:
continue
print(i)
6. pass Statement
The pass
statement is a placeholder that does nothing. It is used as a stub in code development.
for i in range(5):
pass # Placeholder
7. try-except Statement
The try-except
statement handles exceptions (errors) gracefully.
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("Execution complete")
8. Function Definitions (def
)
Functions are defined using the def
keyword.
def greet(name):
return f"Hello, {name}"
print(greet("Alice"))
9. Class Definitions (class
)
Classes define the structure of objects.
class Person:
def __init__(self, name):
self.name = name
def say_hello(self):
return f"Hello, I am {self.name}"
p = Person("Alice")
print(p.say_hello())
10. Import Statement
The import
statement is used to include modules in a program.
import math
print(math.sqrt(16)) # Output: 4.0
11. return Statement
The return
statement is used to send a value back from a function.
def add(a, b):
return a + b
print(add(2, 3)) # Output: 5
12. yield Statement
The yield
statement is used in generators to return a value and maintain the function’s state.
def count_up_to(n):
count = 1
while count <= n:
yield count
count += 1
for number in count_up_to(5):
print(number)
❉ Special Statements
1. Global Statement
The global
statement declares variables that should be treated as global.
def set_global():
global x
x = 10
set_global()
print(x) # Output: 10
2. Nonlocal Statement
The nonlocal
statement is used in nested functions to modify variables in the enclosing (non-global) scope.
def outer():
x = 10
def inner():
nonlocal x
x = 20
inner()
print(x)
outer() # Output: 20
3. Assert Statement
The assert
statement is used for debugging purposes to ensure a condition is True
.
x = 5
assert x > 0, "x should be positive"
4. Del Statement
The del
statement removes a variable or item.
x = [1, 2, 3]
del x[1]
print(x) # Output: [1, 3]
5. With Statement
The with
statement is used for resource management (e.g., opening files).
with open("example.txt", "w") as file:
file.write("Hello, World!")
6. Lambda Statement
The lambda
statement creates an anonymous function.
square = lambda x: x ** 2
print(square(4)) # Output: 16
❉ Advanced Python Statements
1. Decorators
Decorators allow you to modify the behavior of a function or method.
def decorator(func):
def wrapper():
print("Before function call")
func()
print("After function call")
return wrapper
@decorator
def say_hello():
print("Hello!")
say_hello()
2. List Comprehensions
List comprehensions provide a concise way to create lists.
squares = [x**2 for x in range(5)]
print(squares) # Output: [0, 1, 4, 9, 16]
3. Conditional Expressions (Ternary Operator)
A compact form of the if-else
statement.
x = 10
result = "Greater than 5" if x > 5 else "Less than or equal to 5"
print(result) # Output: Greater than 5
4. Set and Dictionary Comprehensions
These are similar to list comprehensions but for sets and dictionaries.
# Set comprehension
squares_set = {x**2 for x in range(5)}
print(squares_set) # Output: {0, 1, 4, 9, 16}
# Dictionary comprehension
squares_dict = {x: x**2 for x in range(5)}
print(squares_dict) # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
5. Context Managers
Context managers are used with the with
statement to manage resources (e.g., file handling, database connections).
class MyContextManager:
def __enter__(self):
print("Entering context")
return self
def __exit__(self, exc_type, exc_value, traceback):
print("Exiting context")
with MyContextManager() as cm:
print("Inside context")
6. else
Clause with Loops
The else
block in loops is executed when the loop terminates normally (not by a break
).
for i in range(3):
print(i)
else:
print("Loop finished without break")
7. else
Clause with Try-Except
The else
block in try-except
is executed if no exceptions are raised.
try:
x = 10 / 2
except ZeroDivisionError:
print("Error")
else:
print("No error occurred")
❉ Conclusion
Python provides a rich set of statements for controlling the flow of programs, managing resources, and structuring code. Mastering these statements is essential for writing efficient and readable Python code. Experiment with these examples to deepen your understanding and unlock Python’s full potential!