Block Statements

Block Statements

Detailed explanations for control statements in Python.

ยท

5 min read

Block statements in Python are created with one or more keywords. Consist of one or several statements indented. All indented statements belong to the block statement. The execution of indented statements is controlled by a condition of a control variable. Sometimes these statements are also called control flow statements.

Decision Statements:

if statement: The if statement allows us to execute a block of code if a condition is true. The basic syntax is:

if condition:
    # block of code to be executed if condition is true

if-else statement: The if-else statement allows us to execute one block of code if a condition is true and another block of code if the condition is false. The syntax is:

if condition:
    # block of code to be executed if condition is true
else: 
    # block of code to be executed if condition is false

if-elif-else statement: We can use the elif keyword (short for else if) to specify a block of code to execute if one condition is true and another is false. The syntax is:

if condition1:
    # block of code to be executed if condition1 is true
elif condition2:  
    # block of code to be executed if condition1 is false and condition2 is true
else:
    # block of code to be executed if both conditions are false

Loops:

for loops: For loops iterate over a sequence executing a block of code for each item. The syntax is:

for item in sequence:
    # block of code to be executed for each item

while loops: While loops execute a block of code as long as a condition is true. The syntax is:

while condition:
    # block of code to be executed while condition is true

Nested Statements

Nested statements in Python refer to statements that are defined within other statements. This allows us to create complex logic and control flows.

Some examples of nested statements in Python are:

  1. Nested if statements: We can define if statements within other if statements to create complex conditional logic.
if condition1:
    if condition2:
        # block of code 
    else:
        # block of code    
else:
    # block of code
  1. if/elif inside while: We can nest an if/elif statement inside a while loop.
while condition:    
    if condition1:
        # block of code   
    elif condition2: 
        # block of code
  1. for inside for: We can nest for loops inside other for loops.
for item1 in sequence1:
    for item2 in sequence2:
        # block of code
  1. for inside if: We can nest a for loop inside an if statement.
if condition:
    for item in sequence:
        # block of code
  1. try/except inside function: We can nest try/except blocks inside functions.
def func():
    try: 
        # block of code
    except Exception as e:
        # block of code

Pass statement

The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute.

For example, in an if statement, the pass can be used to close the block when no action is required:

if condition:
    pass 
# Rest of the code

This is useful when you want to define an empty block now but implement it later.

The pass statement is also useful to close empty functions or class definitions so the code runs without syntax errors:

def empty_function():
    pass

class EmptyClass:
    pass

In Python, indentation is used to delimit code blocks instead of curly braces like in other languages. So if we want to close a code block without reducing the indentation, we can use the pass statement:

if condition: 
    # Some code...
    pass # Closes the if block  
# Still at the same indentation level

In summary, the pass statement in Python allows us to have empty code blocks without causing syntax errors. It essentially means "do nothing" and lets the code run without errors while implementing functionality later.


Break and Continue

The break statement can be used to break out of the current closest enclosing loop.

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

For example:

  for i in range(5):
     if i == 3:
         break
     print(i)
  pass #end for

  for i in range(5):    
     if i == 3:
         continue
     print(i)
   pass #end for

Note: In this example, I used a trick to make the code more readable. I have used a pass with the wrong indentation and comments. This will make the code clear and readable. You will not see this trick in many code-based because is original. I'm the only one teaching this simple trick.


Else clause

For and while loops can have an optional else clause that gets executed when the loop terminates naturally (without breaking out of it). This can be used to execute some code once all iterations are complete.

For example:

  for i in range(5):
      pass
  else:
      print("Loop finished naturally!")

Note: The loop control variables used in for and while loops persist even after the loop has finished. They are not local to the loop. You can use the variable to verify how the loop terminates.


Disclaim: I have done my best to ask the proper questions, so you can learn the topic without asking. This article is created with AI called Rix. Learn and prosper. ๐Ÿ––

ย