Python Statement, Indentation, and Comments
Python syntax refers to the rules you need to follow while coding in python. In this article, we will be looking in-depth into the python syntax. We will look at working with python statements, indentation and comments.
Python Statement
When you write code, you use statements to provide instructions to the interpreter. The interpreter uses these instructions and executes them.
These statements can be of different types.
Print, assignment statements and multi-line are the frequently used statements. Let’s have a look at these:
1. Blank Line Statements in Python
Empty lines in Python get interpreted as false statements and so the python interpreter always ignores blank lines.
2. Assignment Statements in Python
In python, when assigning a value to a variable you use the assignment statement. The values can be of any data type. In python, you don’t have to declare the variable. The declaration happens automatically during execution.
Example of Assignment statements in python
int1=10 string1="This is a sentence" list1=["PythonGeeks",1,2,3,"syntax"] dictionary1={"one":1, "two":2} tuple1=("apple",100) print(f"The datatype of {int1} is {type(int1)}") print(f"The datatype of {string1} is {type(string1)}") print(f"The datatype of {list1} is {type(list1)}") print(f"The datatype of {dictionary1} is {type(dictionary1)}") print(f"The datatype of {tuple1} is {type(tuple1)}")
Output:
The datatype of This is a sentence is <class ‘str’>
The datatype of [PythonGeeks, 1, 2, 3, ‘syntax’] is <class ‘list’>
The datatype of {‘one’: 1, ‘two’: 2} is <class ‘dict’>
The datatype of (‘apple’, 100) is <class ‘tuple’>
The example above shows the assignment of variables to an integer, a string, a list, a dictionary and a tuple. The output shows the values stored in each along with the type of each assignment.
Compound Statements in Python
Multiple statements or a group of statements written together to form compound statements. Compound statements together form a block of code. Every time you work with multiple statements that form a block of code, indentation is important.
Compound statements have a header that helps identify the statement or condition. This header line ends with a colon. And the body of the code has a set of statements, these statements when written should have a proper indentation.
Example of Compound statement in python:
for num in range (1,20): if num > 1: for i in range(2,num): if (num % i) == 0: break else: print(num)
Output:
3
5
7
11
13
17
19
The example above shows how multiple statements together form a compound statement and how the indentation works.
1. Print Statement in Python
When you want to print anything in python the content is written in a print statement.
Example of print statements in python :
print("Welcome to PythonGeeks")
Output:
2. Strings Statements in Python
When you work on an idle shell, you can directly display string statements without using the print function.
Example of Strings Statements in python :
“This article is about python statements indentation and comments'”
Output:
3. Multi-line statement in Python
In python every time you click to enter, the interpreter considers it to be a new line. To write code in multiple lines we use a backslash (\)
Example of Multi-line statements in python:
msg=\ 'this \ is \ how \ you use \ back slash \ to write \ multi-line \ statements' print("the \ message is:",\ msg)
Output:
The example above shows you how to use multiple lines to assign a variable. The output is what you will see after executing the code.
Multi-Statements in One Line in Python
You can also write multiple lines in python by separating each statement with a semicolon.
Example of Multi-Statements in One Line in python:
age = 5;name = "Rohit" print(f"{name}'s age is {age}")
Output:
Here, the semicolon used between the age and name variable allows you to define two variables in the same line.
Python Indentation
Indentation is when you add a blank/white space before a statement. In python, indentation is a very important part of the code. If you don’t use proper indentation, the code won’t run and you’ll get an error stating “IndentationError”.
Indentation is only used in most other programming languages to help make the code look nice. However, in Python, it indicates which block of code a statement belongs to.
Example of Incorrect Indentation in python:
password="password" p=input("please enter a number\n") if(p!=password): print("you have entered incorrect password") else: print("Successfully signed in")
The example above shows you how the code would look if the indentation is incorrect. When you run this code you will get an error message stating “expected indentation block” as shown in the output.
Example of correct Indentation in python:
password="password" p=input("please enter a number\n") if(p!=password): print("you have entered incorrect password") else: print("Successfully signed in")
Output:
password
Successfully signed in
The example above shows you how the code with correct indentation would look. Here as you see there are blank spaces after the if and else line. This indicated the code block for if and else.
Python Comments
In python, you use comments to explain the code. It makes the code more readable. The comments are not displayed when executed. The comment is only read by the programmer developing the code or the programmer using the code.
1. Docstrings Comments in Python
When defining a module, function, class, or method in Python we have to explain what the code is. In such situations, you use Docstrings to help anyone using the code or working on the code understand it better.
Example of docstring comments in python :
def findfactorial(num): """ This function takes input num which is an integer and finds the factorial of the number """ factorial = 1 if num < 0: print(f" {num} is negative and negative numbers do not have factorials") elif num == 0: print(f"The factorial of {num} is 1") else: for i in range(1,num + 1): factorial = factorial*i print(f"The factorial of {num} is {factorial}") num=int(input("enter a number\n")) findfactorial(num)
Output:
5
The factorial of 5 is 120
2. Single-Line Comments in Python
To write a single-line comment in python you use a hashtag (#) followed by the statement.
Example of single-line comments in python :
#taking string (name) as input and storing it in a variable name name=input("please enter your name\n") #taking int (age) as input and storing it in variable age age=int(input("please enter your age\n")) #printing name and age print(f"your name is {name} and your age is {age}")
Output:
apple
please enter your age
20
your name is apple and your age is 20
The example above shows how comments are written in python. You will notice that the comment is not visible when the code is executed.
3. Multi-line comments in Python
There may be situations when comment text does not fit into one line, in such cases you use multi-line comments. Multi-line comments can be written using two methods:
a. Using hashtags (#):
Just like in single-line comments, you can use the hashtag to write multi-line comments. Each time you start a new comment you add a hashtag at the beginning.
Example of multi-line comments using hashtag:
#swapping two numbers #store first number in input a #store second number in input b #set temp =a #set a=b #set b=temp a=100 b=200 print(f"the value of a is {a} and the value of b is {b}",sep="\n") temp=a a=b b=temp print(f"the value of a is {a} and the value of b is {b}",sep="\n")
Output:
the value of a is 200 and the value of b is 100
The example above shows the use of a hashtag to write comments. Here we have used the comments to write the algorithm used to swap two numbers. The execution of the algorithm is shown in the output.
b. Using delimiters (“””):
Sometimes when multiple lined statements need to be written to comments, hashtags may not be helpful. It will cause a break inflow of the statements. In such situations, you can use delimiters for writing comments.
Example of multi-line comments using delimiter:
""" when you use delimiters to write multiple lined comments, this is how it looks.more. """ print("PythonGeeks")
Output:
Frequently asked questions on Python Statement, Indentation and Comments:
Q1. Is there an error in the following code?
num = int(input("Enter a number: ")) if num > 0: print("The number is Positive") elif num == 0: print("Zero") else: print("The number is Negative")
Ans 1. The indentation after the else statement is incorrect. There needs to be a blank space before the print.
Q2. How do you fix the error in the previous code?
Ans 2. Add a blank space before the last print statement.
num = int(input("Enter a number: ")) if num > 0: print("The number is Positive") elif num == 0: print("Zero") Else: print("The number is Negative")
Q3. Give an example of how to differentiate between multi-line and single-line comments?
Ans 3. Below is the code for the same:
"This is a single-line comment" ''' This is multi-line comment! ''' print("welcome to PythonGeeks")
Q4. Why do we need multi-line statements, give an example?
Ans 4. When working with python it is suggested that you limit the length of any single line of code to 79 characters. So when you have larger codes multi-line statements help as in below example:
msg = ("Hello\n" "welcome to \n" "PythonGeeks") print("the message is\n",\ msg)
Output:
Hello
welcome to
PythonGeeks
Q5. How do you assign values to a variable, give an example?
Ans 5. When assigning values to variables, you use the equal sign (=). The memory allocation for variables occurs automatically when you declare the variable. It’s shown in below example
fruits=['apple','banana'] print(fruits)
Output
Summary
This article looks into the python syntax used for python statements, indentation and comments. In python statements, we looked at examples where you use assignment, print and multiline statements along with their outputs.
In python indentation, we had a look at what happens when the code does not have a proper indentation. Finally, we looked at how to write comments in python code and why they are important
Above example: Docstrings Comments in Python, line 5 : factorial = 1
Will generates an error, need to have indentation to line 13