+ 1

what is indentation?

In python what is the role of indentation? Anybody knows so tell me.

22nd Mar 2019, 4:24 AM
Hamza Hassan
Hamza Hassan - avatar
3 Answers
+ 9
Indentation in python is very important as it defines where code blocks start and end. Example I: ------------------------------------------------ number = 2; if number == 3: pass; print("The number is equal to 3."); print("End of code."); ------------------------------------------------ This prints: "The number is equal to 3." "End of code." The first string should not have been printed but since there was no indentation the first print statement was not inside the if statement just like the second print statement. Example II: ------------------------------------------------ number = 2; if number == 3: print("The number is equal to 3."); print("End of code."); ------------------------------------------------ This prints: "End of code." Since the first print statement is indented and so is inside the if statement that doesn't execute and the second print statement is not inside the if statement so it prints. EDIT: Anna, Thank you for the correction, don't use python regularly, had forgotten that.
22nd Mar 2019, 4:57 AM
LynTon
LynTon - avatar
+ 8
Indentation is used in Python so it can infer statement terminators and block braces from whitespace. This means that a semicolon is not required at the end of every declaration but that it can be used to separate multiple commands on the same line. Although C allows free form with whitespace, in this example a compilation error can occur if indentation with nested if else statements is not consistent. Indentation not only helps with organization and readability, it lets a compiler or interpreter know how to parse your code. https://code.sololearn.com/c92Qo7fUMafa/?ref=app
22nd Mar 2019, 6:15 AM
boneSpider
boneSpider - avatar
+ 5
LynTon Actually your first example will result in a syntax error because python necessarily expects at least one indented line after an if statement. You can evade it with 'pass': if number == 3: pass print('The number...')
22nd Mar 2019, 6:01 AM
Anna
Anna - avatar