Indentation in python

Hi,
I am new to learning python
While writing the code, i receive a lot of indentation errors
I was just wondering if someone can help me understand how to indent 4 spaces and when to not have the indentation
Or when the indentation increases to more 4 spaces

You can set up your editor or IDE 's indention settings.
For example, 1 tab = 4 spaces. Whenever you indent a code to the next indentation level, all you need to do is press tab.

1 Like

The indentation has to depends on the logic. Given below are some examples.

Without if, elif, else, def, for, while, most of the time, python interpreter does not require an indentation for the next statement.

x = 10
y = 4
z = x + y
x = [1, 0, 2, 9, 3, 11, 4, 22, 5]
left = 0
right = len(x)
mid = left + (right - left)//2 
x = [x for x in salary if x > 4000]
observe_time # contains a boolean statement 
x = "Time = " if observe_time else ""
salary # is an integer
rating =  5 if salary > 5000 else 4

Most of the time, if, elif, else, def, for, while requires an indentation for the next statement.

i = 10
while i:
[4 spaces]i -= 1
while x > 0:
[4 spaces]#do something
for x in columns:
[4 spaces]#do something
for x in columns:
[4 spaces]#do something
else:
[4 spaces]#do something
for x in columns:
[4 spaces]for y in others:
[4 spaces][4 spaces]print("hello")
if x in df.columns:
[4 spaces]#do something
elif x in other.columns:
[4 spaces]# do something
else:
[4 spaces]#do something
if x in df.columns:
[4 spaces]if x > 4:
[4 spaces][4 spaces]# do something
else:
[4 spaces]print(x)
def print_function():
[4 spaces]print("hello")
def print_function():
[4 spaces]for x in range(10):
[4 spaces][4 spaces]print(x)
1 Like