Python Syntax

Python syntax is the set of rules that define the way the Python program will be written and interpreted.

Indentation

If you’ve worked with other programming languages you probably noticed that blocks of code are usually indicated by braces.

Python uses a different approach to this.

Each block in Python is delimited by indenting all of its statements by the same amount of spaces or tabs in one block.

The number of spaces in different blocks can vary, but the rule of thumb is that you should be consistent to keep your code clean.

Good:

if True:
    print('One')
    print('Two')
else:
    print('Three')

Not recommended:

if True:
    print('One')
    print('Two')
else:
 print('Three')

Bad:

if True:
    print('One')
  print('Two')
else:
    print('Three')

Comments and docstrings

In Python, there are two methods that can be used to annotate Python code.

Comments

Comment use ‘#’ before text message and are terminated by the end of the line.

# This is a comment

They are used to indicate that some parts of the code do.

def rectangle_area():
    # assigning values to variables
    a = 5
    b = 6
    return a*b  # the function multiplies two variables

If you want a comment to span more than one line, you can use multi-line string (“”” or ”’ as a delimiter at the beginning and end of a comment).

def rectangle_area():
    a = 5
    b = 6
    """the function 
    multiplies two 
    variables"""
    return a*b

Docstrings

Dosctring is similar to a comment, but unlike comments, docstrings are not stripped when the code is parsed, but kept throughout the runtime of the program and can be accessed in the debugger with the attribute named __doc__.

class Animal(object):
    """The class's docstring"""

    def eat(self):
        """The method's docstring"""

Statements

Statements in Python typically end with a new line. But you can tell Python to treat a multi-line statement as a single statement.

In the example below the third_value variable is moved to a new line with the line continuation character (\).

first_value = 1
second_value = 2
third_value = 3

result = first_value + second_value + third_value

For such structures as list, tuple or dictionary you don’t use the continuation character (\).

my_list = [1, 2, "three", 4]
my_dictionary = {"key 1": "value 1", 2: 5, 3: []}
my_tuple = ('mathematics', 'biology', 1997, 2000)

Just press Enter and type the next part of the statement. The above code is similar to this code.

my_list = [1, 2, "three", 4]

my_dictionary = {"key 1": "value 1", 2: 5, 3: []}

my_tuple = ('mathematics', 'biology', 1997, 2000)

Strings

To assign a value to a string you have to use single (‘) or double quotes (“). Both variables return the same result.

first_sentence = 'This is a sentence.'
second_sentence = "This is a sentence."

You can also assign string using multi-line statements.

paragraph1 = """This is a
multi-line paragraph. It
returns multiple lines."""

It returns the following result.

This is a
multi-line paragraph. It
returns multiple lines.

If you want to assign a string consisting of multiple lines, and print it as a single line, use the following code.

paragraph2 = "This is a " + \
             "multi-line paragraph. It " + \
             "returns a single line."

This is the result.

This is a multi-line paragraph. It returns a single line.

Case sensitivity

Python is case sensitive. It means that each of the variables below is different.

MyVariable = 1
myVariable = 2
Myvariable = 3
myvariable = 4

Numbers

Numbers in Python can be assigned using multiple forms. These are some of them.

val1 = 0
val2 = -2
val3 = 3.7
val4 = -.7
val5 = 3.5e-2

Reserved keywords

The following words are reserved for Python you cannot create object names using the following words.

andexcecnot
asFalseor
assertfinallypass
asyncforprint
awaitfromraise
breakglobalreturn
classifTrue
continueimporttry
definwhile
deliswith
eliflambdayield
elseNone 
exceptnonlocal 

Blank lines

Blank lines are spaces between code or comments.

1 blank line is required to separate methods and 2 blank lines are needed to separate classes or functions. If you do it differently the interpreter won’t return errors, but you will get warnings.

x = 4
y = 5


# two blank lines
class MyClass1:
    a = 1
    b = 2

    # one blank line
    def method_1(self):
        return self.a

    # one blank line
    def method_2(self):
        return self.b


# two blank lines
class MyClass2:
    c = 3

    # one blank line
    def method_3(self):
        return self.c


# two blank lines
def function_1():
    return x


# two blank lines
def function_2():
    return y