Python Syntax


Python Syntax and Indentation

First, we must define indentation. The term indentation refers to the space or tab added at the beginning of each line. In Python, indentation plays a significant role, we need to indent our code not only for readability but to maintain the syntax as well.

Yes, you read that right. In Python, we maintain the syntax using indentation, which is very different from some other programming languages where we use curly brackets. The start and end of the block are not marked with curly brackets or parenthesis in Python.

Let us see some examples of indentation in the below code:

If we are starting a new block in python, we have to give space or a tab to indicate the start of a new block.

In [1]:
num1 = 10
num2 = 20
if num1 > num2:
    print('num1 is greater then num2')
    print('Thanks for visiting')
else:
    print('num2 is greater then or equal to num1')
    print('Thanks for visiting')
num2 is greater then or equal to num1
Thanks for visiting

In case we don’t give any space or a tab then we get an Indentation Error as shown below.

In [2]:
num1 = 10
num2 = 20
if num1 > num2:
print('num1 is greater then num2')
print('Thanks for visiting')
else:
print('num2 is greater then or equal to num1')
print('Thanks for visiting')
  File "<ipython-input-2-739832c84972>", line 4
    print('num1 is greater then num2')
        ^
IndentationError: expected an indented block

If we give a space instead of a tab, it still works. Note: all the lines in the same block must have the same number of spaces or tabs.

In [3]:
num1 = 10
num2 = 20
if num1 > num2:
 print('num1 is greater then num2')
 print('Thanks for visiting')
else:
 print('num2 is greater then or equal to num1')
 print('Thanks for visiting')
num2 is greater then or equal to num1
Thanks for visiting

Few key points about indentation in Python:

  1. Spaces or Tabs: You can use either spaces or tabs for indentation, but it’s essential to be consistent throughout your code. Mixing spaces and tabs can lead to indentation errors.
  2. Standard Convention: The Python community conventionally uses 4 spaces for each level of indentation. This is recommended by the official Python style guide, PEP 8.
  3. Whitespace: Make sure not to mix tabs and spaces in the same block of code. This can cause indentation errors.
  4. Block Structure: Code blocks, such as those within control flow statements (if, for, while) and functions, are defined by consistent indentation. All statements with the same level of indentation belong to the same block.
  5. No Braces: Python does not use braces to define blocks. The indentation is what determines the structure of the code.
  6. Nested Blocks: Indentation is used to show nested blocks of code. The level of indentation indicates the level of nesting.

Python Indentation in a Nutshell

Let us try to understand python indentation using the image below:

Python Syntax and Indentation

Python Multiline Statements

In python, you can break long statements into multiple lines using the backslash(\). This is also known as Explicit Line Joining.

String without backslash(\). We get Syntax Error.

In [1]:
a = "Content 
in 
multiple 
lines"
print(a)
  File "<ipython-input-1-769b4fe217db>", line 1
    a = "Content
                 ^
SyntaxError: EOL while scanning string literal

String with backslash(\).

In [2]:
a = "Content \
in \
multiple \
lines"
print(a)
Content in multiple lines

Addition without backslash(\). We get Syntax Error.

In [3]:
num1 = 5
num2 = 10
num3 = 15
sum = num1 +
num2 +
num3
print(sum)
  File "<ipython-input-3-65697779a270>", line 4
    sum = num1 +
                ^
SyntaxError: invalid syntax

Addition with backslash(\).

In [4]:
num1 = 5
num2 = 10
num3 = 15
sum = num1 +\
num2 +\
num3
print(sum)
30

Note: We don’t need a backslash to write the content of a list, tuple, or dictionary in more than one line. This is also known as Implicit Line Joining.

List

In [1]:
li = ["list",
     "in",
     "multiple",
     "lines"]

print(li)
['list', 'in', 'multiple', 'lines']

Tuple

In [2]:
tu = ("tuple",
     "in",
     "multiple",
     "lines")

print(tu)
('tuple', 'in', 'multiple', 'lines')

Dictionary

In [3]:
dict = {"1":"dictionary",
     "2":"in",
     "3":"multiple",
     "4":"lines"}

print(dict)
{'1': 'dictionary', '2': 'in', '3': 'multiple', '4': 'lines'}

Whitespace within lines

In Python, white spaces within lines of code are not necessary. But yes, it is always recommended to use whitespace more mindfully to so that the code is readable.

In [1]:
x=10+1
print(x)

x = 10 + 1
print(x)

x             =        10    +                1
print(x)
11
11
11

Multiple Statements in single line

Python also provides us the flexibility to write multiple statements in a single line, separating each with a semicolon; but in general, this is not considered to be a practical approach as this reduces the readability of code.

In [1]:
x=10; y=20;
print(x); print(y);
10
20

Resources

Handwritten Notes

References:

  1. The Python Tutorial
  2. Python Syntax and Semantics
  3. Python Syntax