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:
1 2 3 4 5 |
if True: print('One') print('Two') else: print('Three') |
Not recommended:
1 2 3 4 5 |
if True: print('One') print('Two') else: print('Three') |
Bad:
1 2 3 4 5 |
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 messages and are terminated by the end of the line.
1 |
# This is a comment |
They are used to indicate that some parts of the code do.
1 2 3 4 5 |
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 a multi-line string (“”” or ”’ as a delimiter at the beginning and end of a comment).
1 2 3 4 5 6 7 |
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__.
1 2 3 4 5 |
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 (\).
1 2 3 4 5 |
first_value = 1 second_value = 2 third_value = 3 result = first_value + second_value + third_value |
For such structures as lists, tuples, or dictionaries you don’t use the continuation character (\).
1 2 3 |
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.
1 2 3 |
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.
1 2 |
first_sentence = 'This is a sentence.' second_sentence = "This is a sentence." |
You can also assign strings using multi-line statements.
1 2 3 |
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.
1 2 3 |
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.
1 2 3 4 |
MyVariable = 1 myVariable = 2 Myvariable = 3 myvariable = 4 |
Numbers
Numbers in Python can be assigned using multiple forms. These are some of them.
1 2 3 4 5 |
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.
and | excec | not |
as | False | or |
assert | finally | pass |
async | for | |
await | from | raise |
break | global | return |
class | if | True |
continue | import | try |
def | in | while |
del | is | with |
elif | lambda | yield |
else | None | |
except | nonlocal |
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