Syntax of Python Programming

In this tutorial, we will learn how to write a program in Python, and compare it other programming languages in terms of syntax. We will discuss on indentation, statements, etc.

Statements and Indentation

If you are familiar with other programming languages like Java, C, C#, etc., semi-colon is used to end a statement, and curly braces are used to define a code block, function body, scope, etc.

But in Python, the syntax is quite different. New line separates statements, and indentation define the body of a block, function, or statement.

Let us start with a simple example of defining a string, and printing it.

Python Program

message = 'Hello World'
print(message)
Try Online

Observations from the above program:

  • There are two statements in the above program. The first is an assignment statement, and the second is a function call.
  • Each line is a statement. There is no semi-colon character at the end of each statement to specify that the statement has ended.
  • Both the lines have same indentation. Meaning, they belong to a single block of code.

Now let us write a loop statement and understand about the indentation a little step further.

Python Program

message = 'Hello World'

for i in range(5):
    print(i)
    print(message)
Try Online

Observations from the above program:

  • The first two statements are with same indentation. Therefore, there are only two statements at program level. The first is assignment, and the second is For Loop.
  • Inside the For Loop, there are two print statements with the same indentation. The indentation is four single-space characters. Therefore, these two statements are a block, and is the body of our For Loop.
ADVERTISEMENT

Comments

The comments are used to improve the readability of the program, but are ignored during execution.

In the following program, the first and third line are comments. Comments start with hash symbol #.

Python Program

#initialize message with hello world
message = 'Hello World'
#printing message
print(message)
Try Online

Identifiers

The names of variables, functions, classes, etc., are called the identifiers. “Identifiers” by meaning are those that are used to identify an entity by some name.

Let us consider the following program, and try to mark the identifiers in it.

Python Program

def printer(x):
    print(x)

message = 'Hello World'
printer(message)
Try Online

The name of the function printer is an identifier. The name of the variable message is an identifier. The variable inside the printer function x is an identifier.