Python – Syntax, Comments & Indentation

From the previous tutorial, we have learned to successfully install python in our system. So now let’s begin, to learn to write our first program in python and how to run it. Apart from that, we will master some of the basics like what are comments and indentation and their significance in python. If you wish to be a proficient code writer then this tutorial is for you.

First Python Program for Beginners

We can begin with a simple, yet easy program called “Hello World” python program which is always considered a beginners program for any programming language. We can execute a program in 3 ways. They are:

a) Running python in Interactive Mode

Interactive mode is always the best choice for a beginner to learn python language easily. In interactive mode, the code is executed instantly on hitting the enter Key. Hence interactive mode favors the unique feature of python that is the line-by-line execution of code. Interactive mode is desirable for someone focusing on fewer lines of code and instant results.
To open an interactive interpret prompt you need to open your command prompt first and then type python. The below prompt will appear on the screen.

Command Prompt

Now type the below example showing the syntax of the python print function.

Example: printing “Hello World” program in command prompt

>>> print("Hello, World !!!")
 

Hello, World !!!
  •  “>>>” means is ready to run and interpret the commands.
  •  print() is a function used to print the message given inside the braces. Always enclose a message inside either single (‘……..’)or double quotes (“…….”).
  • As soon as you hit the enter key output will appear on the subsequent line.

If any error happens in the code then syntax error will be outputted instead of the result.

SyntaxError: EOL while scanning string literal

>>> print('Hello World!!!)
  File "", line 1
    print('Hello World!!!)
                         ^ 

Note: Use the exit() function to leave python in interactive mode.


b) Running Python in Scripting Mode

Another basic mode to execute a python program is using the scripting mode in which we need to write the codes in a file (helloworld.py) and will execute the file later.

Steps to write a program in scripting mode:

  1. Open the Notepad editor and type the “Hello World !!!” program as shown below.

    Python Hello World
  2. Save the file as helloworld.py

  3. Now open the command prompt and establish a path using the command “cd”. In the above example python program is saved in a folder named “PY PRO” which is located on the Desktop. Using the cd (change directory) command we have changed the directory and established a path to run the program. Command Prompt
  4. To execute the program the syntax is Command Prompt
  5. On hitting enter Key results will be printed in the following line.

Unlike other programming languages, Python matters the order of execution a lot. To prove the significance of line-by-line execution clearly, let’s consider the below examples printing some geometrical shapes and their changes regardless of the mode.

Example: Printing geometrical shape-inverted triangle

print("__________")
print("\        /")
print(" \      / ")
print("  \    /  ")
print("   \  /   ")
print("    \/    ")


Output

__________
\        /
 \      / 
  \    /  
   \  /   
    \/  

From the above example, we can understand that Python runs its codes in an orderly manner and hence python matters its instruction a lot. To illustrate that the above example can be modified a little bit and see the difference.

Example: Printing geometrical shape – line by line execution illustration

print("\        /")
print(" \      / ")
print("__________")
print("  \    /  ")
print("   \  /   ")
print("    \/    ")

Output

\        /
 \      / 
__________
  \    /  
   \  /   
    \/  

The major disadvantage of scripting mode is it takes more time to compile.


c) Running Python using IDE

We can execute python in yet another way, that is, using an Integrated Development Environment. An IDE works much better than a plain Text editor because of the features enabled in it. IDE allows quick editing, execution, and lot more features that can elevate the speed and productivity of code. Some of the IDE’s that you can choose from are listed below.

  • Pycharm
  • Spyder Python
  • Sublime Text 3
  • Eclipse

If you have any of these IDE’s in your system you can use the same for learning the python programming language and if not you can download it and use it for your convenience.

Python Comments

So far we have learned about the different ways to execute programs in python. Now let’s master writing clean and precise code. One should have to prosper their skills on commenting to make the code readable to everyone.

How to write comments in python?

To improve the transparency of code, developers use python comments. Python comments are usually written with a hash(#) character following some statements or texts. A comment can be placed at the beginning of a line or through the line.  Comments at the beginning are used to describe the program or the python script. Inline comments give the meaning of the code if it is complex or difficult to understand. Considering the fact that comments are to elucidate code, python does not interpret the comments and remains inactive throughout the code.

Example: How to create a comment in python


#program to find the sum and difference of two numbers
A = 5       #A is a variable 
B = 3          #B is a variable
print("A+B = ",A+B) #prints the sum of A and B
print("A-B = ",A-B) #prints the difference of A and B 

#programs ends


Importance of Python Comments

Comments are considered as one of the essential parts, not only in the python programming language but in other programming languages too. This is because of the following reason.

  • It gives clarity to the code
  •  Comments aid other developers and the developer itself to cognize the python code and its workflow easily.

Multiple line commenting

We are now familiar with single-line comments from the previous example. But what if we need multi-line commenting. In reality, python has no specific format for multi-line commenting. But as always there should be some way or the other. One way is by adding a hash character initially before each consecutive line as shown below.

Example: Multiple line commenting

# this is 
#one way of
#writing multi line comment 

The other way of commenting in python language is by encasing the desired texts inside a triple quote set either (“ “ “) or (‘ ‘ ‘ )as given below.

Example: Multi-line commenting using a triple quote

"""
this is 
one way of
writing multi line comment
 """

What is the significance of Indentation in python?

Indentation is a key feature that we must learn before starting to write code. In python, indentation plays a major role as if you don’t know to indent the sequence correctly in python then you will be getting an indentation error and your program will get stuck without being complied. 

What is python indentation?

Indentation refers to the use of space and tab in python code to make them a block. Through Indentation we are dividing the sequences into blocks which helps the compilers or interpreters to understand the order in which sequence of codes has to execute.

Programming languages like C, C++, Java, etc, use curly braces to show the beginning and end of the block of code. Similarly, python uses the indents to specify the start and end of the block. A block is a collection of statements and declarations. If two or more statements follow the same indentation(vertical line) then they belong to a block.

Pictorial representation of indentation

 

Pictorial representation of indentation

 

In the above pictures

  • Block 1 contains  statements 1,2 and 7
  • Block 2 contains  statements 3,5 and 6
  • Block 3 contains  statement 4

How to indent python code?

The below example is an illustration of indenting. The below program shows the working of an if statement.

Example: How to use indentation

if  A==10      #block 1  begins
 Print(“A  contains value 10”)    #block 2 begins         
else :       #block 1 continues
 Print(“A  does not contain value 10 ”)   #block 2 continues
Print(“All done!”)     #block 1 ends  

Output

A contains value 10
All done

It is pretty clear from the above program how the indentation works in the python programming language. The density of indentation depends on the user however it must be consistent throughout the particular block. So, Indentation in python is important and it elevates both structural easiness and readability of code.

Note: By default python use 4 spaces for indentation.