Indentation

In this guide, I’ll be showing you what’s Indentation in Python!

Introduction

In other programming languages, Indentation is only used so that it is easier to read (from what I’ve heard). But Indentation is Python is very important!

Python Indentation is a way of telling the computer that a group of statements belongs to what part of the program. If you don’t properly indent your code, the code will not work.

n = 10

if n > 5:
print("n is greater than 5")
else:
print("n is not greater than 5")

To indent code, press the “Tab” key on the keyboard.

In this example code, we have an If statement. To know more about If statements, click here!

To indicate that the print statements “n is greater than 5” and “n is not greater than 5” are in it, we use Indentation, like this-

n = 10

if n > 5:
     print("n is greater than 5")
else:
     print("n is not greater than 5")

Looks neater, doesn’t it? If you have a loop in your code and don’t use Indentation, the computer will display an error message.

Examples

Indentation is also used in nested loops

weather = input("Is the weather great today?")

if weather == "no":
     rainy = input("Is it raining?")
     if rainy == "yes":
          print("Don't go outside!")
     else:
          print("Okay")
else:
     print("Enjoy your day!")

As well as subprograms

def addition(num_1,num_2):
     added_num = num_1 + num_2
     return added_num

Conclusion

That’s all for this Python guide! Hope you found it useful.

Leave a Reply