
In this tutorial, we will teach you everything you need to know about the basics of Python syntax of Python, variable declaration rules, reserved keywords, and code structuring rules.
To get started with Python you need to be familiar with its syntax and predefined keywords and rules to apply in order to properly arrange and effectively use these keywords together whenever it is necessary.
In our previous tutorial, we showed how to write and run simple Python code in the VS code editor. Therefore, there are some syntax rules you cannot violate in order to write valid Python code. To be a successful programmer, you must learn how to write clean, easy-to-read, and easy-to-understand code.
Table of Contents
The most common syntax rules of Python include:
Python Indentation
Indentation refers to the practice of adding white spaces at the beginning of a line of code. This practice enhances the readability of the written code and defines the hierarchical structures of the code (e.g. Python code).
In Python indentation is used to indicate the scope of a block of code, especially when using a control flow (e.g. loops and if statements). If you ignore Python indentation during the control flow it will trigger an error (syntax error).
The following Python code ignores the indentation and triggers a syntax error. Becouse, the second line of the code must be indented under the for loop condition, it means that, the second line will be executed as long as the for
loop condition is True
.
for i in range(5):
print("Hello, World!!")
The output of the syntax error reads as follows:
File "e:\Hello.py", line 2
print("Hello, World!!")
^
IndentationError: expected an indented block after 'for' statement on line 1
The following Python code uses indentation to specify a block of code to be executed as long as the conditional statement is True.
for i in range(5):
print("Hello World")
The output reads as follows:
Hello, World!!
Hello, World!!
Hello, World!!
Hello, World!!
Hello, World!!
The number of white spaces (indentation ) to be used is an open choice to the programmer but Python uses four white spaces as a default indentation and some code editors such as VS Code automatically adjust the default white spaces in Python.
Python Comments
Comments are used to explain the written Python code and the compilers ignore execution. While it can also be used to prevent a piece of code to be executed. This enhances the readability and understandability of the code in the future.
There are two types of comments in Python
- Single-line comment: This mainly started # (hashtag) symbol.
This comment can be placed at a new line or at the end of the code statement and it will affect the execution of that line as the compiler ignores it.
- Multi-line comment: Although Python does not support multiline comments in a special syntax instead it allows us to use a multiline string as triple quotes and place your comments inside a single
'''comment'''
or double"""comment"""
triple quotations.
# This is a single line comment
print("Hello, World!!")
print("I Love Python") # This is another comment
The output should read as follows:
Hello, World!!
I Love Python
Comment can also be used to prevent a piece of code to be executed by the compiler. This means we tell the compiler to ignore that code that has a # symbol at the front.
# print("Hello, World!!")
# The above line should not be executed
print("I Love Python")
The output should read as follows:
I Love Python
If you need to add multiple lines of comment in your code file, you need to use the # symbol in front of each line, if this is too confusing, the solution will be a multiline comment.
The following example shows how to write a multi-line comment.
"""
A multi-line comment
is another option
to explain your code
"""
'''
A multi-line comment
with single triple quotes is another option
to explain your code
'''
print("Hello, World!!")
The output reads as follows:
Hello, World!!
Note: In Python multi-line strings are used to the string values, however, Python will ignore these string values as long as it is not assigned to a variable. Therefore it is common sense trick to use as a comment syntax
Python Variables
Python variables or identifiers are created to store a value. Each variable must have a name (short names are mostly preferred). However, there are some rules to follow in order to give a name to a variable.
This example shows a variable name called ‘car’ assigned a string value of ‘Toyota’
car = 'Toyota'
Therefore there are some rules to be aware of to declare a variable in the correct syntax. Here are the rules for naming Python variables.
- A variable name can only start with a letter (alphabet) or underscore (
-
). - A variable name cannot be started with a number.
- A variable name cannot contain white spaces.
- Variable names are case-sensitive (e.g. car, CAR, and Car are different).
- Variable names cannot be any of the reserved keywords in Python.
- A variable name cannot contain special characters (e.g.@,&,!, @, etc).
The following example illustrates some legal and illegal variable names and their reasons.
# Legal Variable Names
car = 'Tesla' # Started with a letter and it is not a Python Keyword
_car = 'BMW' # Started with underscore (_)
car3 = 'Honda' # Started with a letter and can contain number
car_4 = 'Kia' # Started with a letter and can contain number and _
int_car = 4 # Started with a letter and they int_car is not a keyword
# Illegal Variable Names
1car = 'Tesla' # Started with a number
_car! = 'BMW' # Contain a special charecter (!)
car 3 = 'Honda' # contain a white space
car & 4 = 'Kia' # contain a special charecter (&) and white space
for = 4 # for is a reserved Python keyword
Note: Rules of naming variables can also be applied to other identifiers given to the Python Classes, Methods, etc.
List of Python Words
Reserved Keywords are special-purpose keywords that cannot be used in naming variables, classes, methods/functions. These keywords can only be used for their intended purpose and to avoid code ambiguity and misinterpretation during the Python code execution.
Here is the list of Python-reserved keywords:
False | try | yield | not | return |
nonlocal | lambda | raise | as | with |
continue | import | while | if | None |
finally | else | del | and | except |
break | pass | assert | in | elif |
global | True | from | def | class |
is | for | or |
Note: All the Python-reserved keywords are case-sensitive and must be written the way they are. Most of the keywords are in lowercase except for Non, True, and False.
Conclusion
In this tutorial, we learned the Python syntax rules that everybody should follow in order to write correct Python code that will not violate the execution procedure of the language. These guidelines and examples provided above are helpful for beginners. For example, we have discussed the indentation rules, comments, and variable declaration rules in Python and many more. All these are beginner essentials when writing code that can easily be understood or read or maintain in the future.
Key Terms
Python Syntax, Python Indentation, Python Comments, Naming Variables, Reserved Keywords, and Practical Examples.