Indentation

What Is Indentation?

  • Indentation is the space at the beginning of a line of code in Python.

Why Is It Important?

  • Python uses indentation to group lines of code together.
  • Instead of using curly braces {} like other languages, Python uses spaces.

Basic Rules:

  1. Same Number of Spaces:
    • All lines in a block must have the same number of spaces.
    • Example:

      def myFunction():
          print('hello')
          print('hello world')
      
  2. Consistency:
    • Use the same number of spaces for each line in a block. The Python community usually uses four spaces.

Exercises and Examples:

  1. Correct Indentation:

    def myFunction():
        print('hello')
        print('hello world')
    
    • Both print statements have the same number of spaces.
  2. Incorrect Indentation:

    def myFunction():
      print('hello')  # 2 spaces
       print('hello world')  # 3 spaces (This will cause an error)
    
    • Result: IndentationError: unexpected indent
  3. Nested Blocks:

    • When you have a block inside another block, the inner block needs more spaces.
    if a == 2:
        print('a is 2')
        if a % 2 == 0:
            print('a is even')
    
    • The inner block (inside the if statement) has more spaces.

Common Mistake:

  • If you don’t use the same number of spaces in a block, Python will give you an "IndentationError."

IndentationError:

  • This error occurs when the indentation is not consistent. It can happen if you mix spaces and tabs or if the number of spaces is different.

Summary:

  • Indentation in Python is essential to organize and group lines of code together. Always use the same number of spaces for each level of indentation. It helps keep your code clean and error-free!