Python – Syntax

Python Indentation

In contrast to C++ and Java, Python employs indentation to identify a code block. Spaces at the beginning of a line of code are referred to as indentation. In the example below, the indentation for a block of code is two spaces.

Let us see the Python – Syntax :

 

a = 100
b = 10
if a > b:
  print(a,"is greater than", b)
else:
  print(a,"is less than", b)

 

The output of the above code will be:

100 is greater than 10

Indentation should be at least one space deep, and it should be fixed inside a code block. In the example below, first if a block of code has been indented with two spaces, and then if a block of code has been indented with four spaces.

 

a = 100
b = 10
if a > b:
  print(a,"is greater than", b)

if a > b:
    print(a,">", b)

 

The output of the above code will be:

100 is greater than 10
100 > 10

 

If a block of code is not indented or has a different indentation, Python throws an error. In the example below, first if no indentation was used in the code block, and then if a different indentation was used in the code block (two spaces and four spaces).

 

a = 100
b = 10
#indentation is not given
if a > b:
  print(a,"is greater than", b)

#different indentation is given
if a > b:
  print(a,"is greater than", b)
    print(a,">", b)


 

The output of the above code will be:

IndentationError: unexpected indent

Python Variables

Python does not need to declare a variable or its data type, unlike other programming languages. When a value is assigned to a variable, the data type is set. The = operator is used to assign a value(s) to the variable.

 

#store number in the variable 'x'
x = 15
print(x)

#store text in the variable 'y'
y = 'Hello'
print(y)

#store sequence in the variable 'z'
z = [1, 2, 3]
print(z)


 

The output of the above code will be:

15
Hello
[1, 2, 3]

Python Comments

The goal of comments in computer code is to provide in-code documentation. It improves the readability of the code, making it easier to edit afterwards. It begins with # and finishes with the line’s conclusion. Anything from # to the end of the line is a single line comment, and the compiler will disregard it.

 

Example:

The following example demonstrates how to utilise comments in Python. When the compiler runs the code, it ignores comments.

 

# first line comment
print('Hello World!.') # second line comment


 

The output of the above code will be:

Hello World!.

 

Leave a Reply

Your email address will not be published. Required fields are marked *