In This Article
One of the main reasons behind Python’s popularity is because of its so simple syntax. Any task that may take up a few lines of code in other languages like C++ or Java, can be done in fewer lines of code in Python.
As a matter of fact, Python programs can be executed by writing directly in the Command Line. The simplicity of Python syntax has led some to call it executable pseudocode. Python syntax has many similarities with languages like C, Java, etc. It also has many major differences as compared to them. We are going to discuss them in this article.
Comments Syntax in Python
Comments in any programming language(not just in Python) are a very useful tool to be considered while writing code. It helps us to explain our code in a better way to others who might be reading it later. It is also used for debugging purposes.
There are usually two types of comments in Python:
- Single-line comment.
- Multi-line comment.
Single-line Comments
They are used in a singular line only. They begin by using a #(hash) symbol.
Example:
# print out hello world to the user
print("Hello World!")
The output will be:
Hello World!
Note: Here the line starting with # does not get executed because it is a comment.
Multi-line Comments
They are used to write multiple lines of comment. They begin with three apostrophes ”’ and also end with ”’.
Example:
''' This is used to
print out
hello world
to the user '''
print("Hello World!")
The output of this will be:
Hello World!
Indentation & Whitespaces syntax in Python
In other programming languages like C++ or Java, we use semicolons (;) to finish a particular line of code. A block of code in these languages is written within second brackets or braces ({}).
In Python, we do not use such syntax for writing our code. Here we use whitespaces and indentations to write our code. We use whitespaces to denote the ending of a line and indentation to denote any block certain block of code.
The code looks more readable and clear in comparison with other programming languages.
Some of the rules for indentation are:
- All lines in a block of code must use the same indentation.
- Use colon(:) to mark the start of a block of code and then press Enter.
- Usually, we use four spaces to mark a block of code, but a single space can also be considered a block of code.
- A block can have inner blocks with the next level of indentations.
Example:
int i=5
if i<10:
print("The value of i is less than 10.")
The output will be:
The value of i is less than 10.
Note: Here the print statement is inside an if block of code.
Multiple-line code in Python Syntax
We can write long statements in multiple lines by using the backslash (\) character.
Example:
int i=5
if i>3 and\
i<10 and\
i==5:
print("The value of i is less than 10.")
The output of this code will be:
The value of i is less than 10.
Note: Here we write the if block using the backslash (\) character for writing it in multiple lines.