13. Indentation#

I have seen memes of people fighting about opening braces, whether they should be starting in the same line or in next line in the programming languages like C, Java etc… πŸ‘»

Types of using curly braces

Python Developers be like: Hold my Beer 🍺

Python developers: we don't do that here

In Python, we don’t use curly braces for grouping the statements. Instead, we use Indentation.

Each group of statements are indented using spaces or tabs.

class Example:
    # Every method belonging to a class must be indented equally.
    def __init__(self):
        name = "indentation example"

    def check_for_odd_or_even(self, number: int):
        # Everything that belongs to this method are indented as well.
        if number % 2 == 0:
            print(f"{number} is even.")
        else:
            print(f"{number} is odd.")


# We can see that the say_hello_multiple_times is not indented inside the Example class.
# Hence, say_hello_multiple_times function doesn't belong to Example class.
def say_hello_multiple_times(count: int):
    for _ in range(count):
        # Loops or conditions are also needed to be intended.
        print("Hello")

PEP-8 recommends to use 4 Spaces instead of Tabs. Although using of Tabs do work, but ensure not to mix both tabs and spaces, as you might get TabError for such indentations.

13.1. A meme on indentation 😜#

If using a normal text editor like notepad where it doesn’t show the warnings or errors, sometimes we might get errors due to wrong indentation or mix usage of both tabs and spaces, we get an error and it would be tricky to resolve it as it is invisible.

Get Error for extra space