Python Syntax#

The syntax is the language structure that makes Python and consists of Reserved keywords that specifies the structure, the Indentation that specifies the context of those keywords, and Comments that specifies which lines or sections to ignore.

Reserved keywords#

The Python language reserves a small set of keywords that cannot be used as variable names, function names, or any other identifiers:

Keyword

Description

and

A logical operator

as

To create an alias

assert

For debugging

break

To break out of a loop

class

To define a class

continue

To continue to the next iteration of a loop

def

To define a function

del

To delete an object

elif

Used in conditional statements, same as else if

else

Used in conditional statements

except

Used with exceptions, what to do when an exception occurs

False

Boolean value, the result of comparison operations

finally

Used with exceptions, a block of code that will be executed no matter if there is an exception or not

for

To create a for loop

from

To import specific parts of a module

global

To declare a global variable

if

To make a conditional statement

import

To import a module

in

To check if a value is present in a list, tuple, etc.

is

To test if two variables are equal

lambda

To create an anonymous function

None

Represents a null value

nonlocal

To declare a non-local variable

not

A logical operator

or

A logical operator

pass

A null statement, a statement that will do nothing

raise

To raise an exception

return

To exit a function and return a value

True

Boolean value, the result of comparison operations

try

To make a try…except statement

while

To create a while loop

with

Used to simplify exception handling

yield

To end a function returns a generator

Indentation#

Python depends on indentation to follow the correct flow of execution. In the example below, we see that there is a possible error as Hello Jack. is being printed before anything else. Many will assume it will be printed after Hello John. as it is directly after it, but indentation wise it isn’t part of the main() function.

Example with valid indentation#
 1#!/usr/bin/env python3
 2
 3def main():
 4    if 1 > 2:
 5        print("Hello World.")
 6    print("Hello John.")
 7
 8print("Hello Jack.")
 9
10
11if __name__ == "__main__":
12    main()
The output of the example above#
1Hello Jack.
2Hello John.

If we try to correct this error by adding a space before the print statement, then Python still gives an error as the indentation doesn’t match all other levels. Python is very similar to YAML and all the indentations needs to be the same. See PEP 8 for a complete set of rules about indentation.

Example of an indentation error#
 1#!/usr/bin/env python3
 2
 3def main():
 4    if 1 > 2:
 5        print("Hello World.")
 6    print("Hello John.")
 7print("Hello Jack.")
 8
 9
10if __name__ == "__main__":
11    main()
Output when running the file with broken indentation#
1  File "/workspaces/learning-python/hello.py", line 7
2    print("Hello Jack.")
3                        ^
4IndentationError: unindent does not match any outer indentation level

Note

Python has no hard guideline on indentation and while most developer choose to use 4 spaces, the requirements is to have at least 1 space for each level of indentation.

Comments#

Any line that starts with # will be ignored by Python. The example below will only print Hello John. as line 7 in the example below.

Example with a line commented out#
 1#!/usr/bin/env python3
 2
 3def main():
 4    if 1 > 2:
 5        print("Hello World.")
 6    print("Hello John.")
 7    # print("Hello Jack.")
 8
 9
10if __name__ == "__main__":
11    main()
Output#
1Hello John.

Multiline comments can be done by starting every line with the #-sign as is shown in the example below on lines 7 and 8.

Example#
 1#!/usr/bin/env python3
 2
 3def main():
 4    if 1 > 2:
 5        print("Hello World.")
 6    print("Hello John.")
 7    # print("Hello Jack.")
 8    # print("Hello James.")
 9
10
11if __name__ == "__main__":
12    main()
Output#
1 Hello John.

For multiline comments Python also supports comments between triple quotes as in the example below on lines 7 to 10. This way of adding comments is also used for documentation but it is not import to understand right now.

Example#
 1#!/usr/bin/env python3
 2
 3def main():
 4    if 1 > 2:
 5        print("Hello World.")
 6    print("Hello John.")
 7    """
 8    print("Hello Jack.")
 9    print("Hello James.")
10    """
11
12
13if __name__ == "__main__":
14    main()
Output#
1Hello John.