Python Tutorial

Python Flow Control

Python Functions

Python Data Types

Python Date and Time

Python Files

Python String

Python List

Python Dictionary

Python Variable

Python Input/Output

Python Exceptions

Python Advanced

Python Code Blocks and Indentation

In Python, code blocks and indentation are used to define the structure of the program. Unlike other programming languages that use curly braces {} to define the scope of code blocks, Python uses indentation to indicate the scope.

Here's a tutorial on Python code blocks and indentation:

  • Indentation:

In Python, indentation is essential for defining the scope of code blocks. Each level of indentation consists of a consistent number of spaces or tabs. Although both spaces and tabs can be used for indentation, it's recommended to use 4 spaces per indentation level, as specified in PEP 8, the Python style guide.

# Correct indentation using 4 spaces
def my_function():
    print("This is inside the function")
  • Code blocks:

A code block in Python is a group of statements that have the same indentation level and are executed together. Code blocks are used to define functions, loops, conditional statements, and other structures.

Here are some examples:

  • Function definition:
def my_function():
    print("This is inside the function")
    print("This is also inside the function")
  • Conditional statements:
if 5 > 3:
    print("5 is greater than 3")
else:
    print("5 is not greater than 3")
  • Loops:
for i in range(3):
    print("Iteration", i)
    print("Inside the loop")
print("Outside the loop")
  • Nested code blocks:

Python allows you to nest code blocks by using multiple levels of indentation. This is useful when you need to define a function within another function, or when you have nested loops or conditional statements.

def outer_function():
    print("Inside the outer function")

    def inner_function():
        print("Inside the inner function")

    inner_function()

outer_function()
  • Indentation errors:

When the indentation is not consistent, Python will raise an IndentationError. This error occurs when there are mixed spaces and tabs, or when the number of spaces is not consistent across the code block.

Example:

def my_function():
  print("This is inside the function")
    print("This is incorrect indentation")

This code will raise an IndentationError:

  File "<stdin>", line 3
    print("This is incorrect indentation")
    ^
IndentationError: unexpected indent

To fix the error, make sure to use consistent indentation throughout your code.

In summary, Python uses indentation to define code blocks, and it's important to use consistent indentation to avoid errors. Use 4 spaces per indentation level, as recommended by PEP 8, and ensure that your code blocks are properly indented to define the structure of your program.