Python syntax is the set of rules that define the way the Python program will be written and interpreted.
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.
Comments and docstrings
In Python, there are two methods that can be used to annotate Python code.
Comment use ‘#’ before text message and are terminated by the end of the line.
They are used to indicate that some parts of the code do.
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).
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__.
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 (\).
For such structures as list, tuple or dictionary you don’t use the continuation character (\).
Just press Enter and type the next part of the statement. The above code is similar to this code.
To assign a value to a string you have to use single (‘) or double quotes (“). Both variables return the same result.
You can also assign string using multi-line statements.
It returns the following result.
If you want to assign a string consisting of multiple lines, and print it as a single line, use the following code.
This is the result.
Python is case sensitive. It means that each of the variables below is different.
Numbers in Python can be assigned using multiple forms. These are some of them.
The following words are reserved for Python you cannot create object names using the following words.
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.