Python uses statements to control the flow of a program. These include assigning values to variables, making decisions with if, repeating code with loops (for, while), handling errors with try, defining functions and classes, and more. A key feature is dynamic typing, meaning a variable can hold any type of data (like a number, then text) without you having to declare its type first.
Python has below statements.
- The assignment statement, using a single equals sign =
- The if statement, which conditionally executes a block of code, along with else and elif (a contraction of else if)
- The for statement, which iterates over an iterable object, capturing each element to a variable for use by the attached block; the variable is not deleted when the loop finishes
- The while statement, which executes a block of code as long as boolean condition is true
- The try statement, which allows exceptions raised in its attached code block to be caught and handled by except clauses (or new syntax except* in Python 3.11 for exception groups);[85] the try statement also ensures that clean-up code in a finally block is always run regardless of how the block exits
- The raise statement, used to raise a specified exception or re-raise a caught exception
- The class statement, which executes a block of code and attaches its local namespace to a class, for use in object-oriented programming
- The def statement, which defines a function or method
- The with statement, which encloses a code block within a context manager, allowing resource-acquisition-is-initialization (RAII)-like behavior and replacing a common try/finally idiom[86] Examples of a context include acquiring a lock before some code is run, and then releasing the lock; or opening and then closing a file
- The break statement, which exits a loop
- The continue statement, which skips the rest of the current iteration and continues with the next
- The del statement, which removes a variable—deleting the reference from the name to the value, and producing an error if the variable is referred to before it is redefined [c]
- The pass statement, serving as a NOP (i.e., no operation), which is syntactically needed to create an empty code block
- The assert statement, used in debugging to check for conditions that should apply
- The yield statement, which returns a value from a generator function (and also an operator); used to implement coroutines
- The return statement, used to return a value from a function
- The import and from statements, used to import modules whose functions or variables can be used in the current program
- The match and case statements, analogous to a switch statement construct, which compares an expression against one or more cases as a control-flow measure
Now we will see the statements with some examples below
Assignment Statement (=)
The assignment statement (=) binds a variable name to a value as a reference to a separate, dynamically allocated object.
name = "Mithran" # 'name' now refers to the string "Mithran"
age = 6 # 'age' now refers to the number 6
Conditional Statements (if, elif, else)
Executes code blocks based on conditions.
temperature = 25
if temperature > 30:
print("It's hot!")
elif temperature > 20:
print("It's pleasant.") # This will be printed
else:
print("It's cold.")
Loop Statements (for, while)
- for: Iterates over items in a list, string, or other iterable.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Output:
# apple
# banana
# cherry
- while: Repeats as long as a condition is true.
count = 3
while count > 0:
print(count)
count -= 1 # Decrease count by 1
# Output:
# 3
# 2
# 1
Loop Control (break, continue)
- break: Exits the loop immediately.
for number in [1, 2, 3, 4, 5]:
if number == 3:
break
print(number)
# Output:
# 1
# 2
- continue: Skips the rest of the current iteration and moves to the next.
for number in [1, 2, 3, 4, 5]:
if number == 3:
continue
print(number)
# Output:
# 1
# 2
# 4
# 5
Error Handling (try, except, finally)
Catches and handles exceptions (errors).
try:
result = 10 / 0 # This will cause a ZeroDivisionError
except ZeroDivisionError:
print("You can't divide by zero!") # This is printed
finally:
print("This always runs, error or not.") # This is also printed
Function and Class Definition (def, class)
- def: Defines a function.
def greet(name):
return f"Hello, {name}!"
print(greet("Mithran")) # Output: Hello, Mithran!
- class: Defines a class for object-oriented programming.
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
return "Woof!"
my_dog = Dog("Rocky")
print(my_dog.bark()) # Output: Woof!
Resource Management (with)
Ensures resources (like files) are properly closed after use.
# The file is automatically closed when the 'with' block ends.
with open('myfile.txt', 'r') as file:
content = file.read()
print(content)
Other Important Statements
- del: Deletes a variable.
x = 100
del x # The variable x is now gone
# print(x) # This would cause a NameError
- pass: A placeholder that does nothing.
def an_empty_function():
pass # We can't leave this blank, so we use 'pass'
- assert: Checks if a condition is True; used for debugging.
x = 5
assert x > 0, "x should be positive" # Nothing happens
# assert x < 0, "x should be negative" # This would raise an AssertionError
- yield: Returns a value from a generator function, pausing its state.
def count_up_to(n):
count = 1
while count <= n:
yield count # Pauses here and returns the value
count += 1
for num in count_up_to(3):
print(num)
# Output:
# 1
# 2
# 3
- return: Exits a function and returns a value.
def add(a, b):
return a + b
result = add(2, 3) # result is now 5
- import / from: Brings in code from other modules.
import math # Import the entire math module
print(math.sqrt(16)) # Output: 4.0
from datetime import date # Import only the 'date' class
today = date.today()
print(today) # Output: 2023-10-27 (or today's date)
- match / case (Python 3.10+): Like a powerful switch statement.
status_code = 404
match status_code:
case 200:
print("Success")
case 404:
print("Not Found") # This will be printed
case _: # The default case
print("Unknown status")
- raise: Manually triggers an exception.
if some_condition_is_bad:
raise ValueError("This is an error message")