For more information specifically on the “why” aspect of indentation in Python, I’d recommend consulting the official Design FAQ.
As far as some of the basic rules, in most places you would use normally curly braces {}
in other languages, you instead use a colon :
followed by 4 spaces [1] of indentation. For example, in C, C++, C#, Java, or most other C-like languages:
if (condition) {
do_something();
}
else {
do_another_thing();
}
In Python:
if condition:
do_something()
else:
do_another_thing()
Similarly in while loops or for loops:
while (1) {
...
}
for (int i = 0; i < 10; i++) {
...
}
while True:
...
for i in range(10):
...
The same applies to subroutine definitions (for functions and methods), class definitions, try-except, and other types of statements (such as Python’s with
statement). For more examples, see https://docs.python.org/3/reference/compound_stmts.html.
Note that the indentation is technically optional for statements that only have a scope of one line, I.E. if conditional: do_something()
, is valid code. You can also use scopes with multiple parts on a single line with a semicolon using if conditional: do_something(); do_another_thing()
, but this is discouraged outside of a few specific use cases [2]. 90% of the time, it’s preferable to use indentation for the sake of readability.
[1] - 4 is technically not the only syntactically valid number of spaces, and tabs can also be used (as long as they aren’t mixed). For more technical details, see https://docs.python.org/3/reference/lexical_analysis.html#indentation.
[2] - A couple specific use cases of the semicolon to combine multiple parts into a single line being useful is when executing a few lines of code with `python -c “do_something(); do_another_thing()” and for benchmarking a few lines of code with timeit. I’d recommend against it for most normal code though.