Python Basics #03 – Python Syntax

In this part of the Python Basics tutorial, we will learn about the syntax used in python.

Indentation in Python

Indentation is the most important part of python syntax. Make sure to never mess this up.
It refers to the spaces at the beginning of a code line.
Most languages use spaces to improve code readability but, python uses indentation to indicate a block of code.

Consider the following block of code.

# Code 1
for i in range(0,10):
    print(i)

# Code 2
x = 5
if 20 > x:
    print("x is smaller than 20.")
print(x)

This codes are correct and hence, executed successfully.

Now, consider the blocks of code below.

# Code 1
for i in range(0,10):
print(i)

# Code 2
x = 5
if 20 > x:
    print("x is smaller than 20.")
  print(x)

The above codes fails to execute and give an “Indentation error”.

You will have to use the same number of spaces in the same block of code, otherwise, Python will give you an error.
In practice, it is often better to use “tabs” in comparison to “spaces”.

Comments in Python

Commenting is used for in-code documentation. It is generally good and recommended practice to follow.

There can be 2 types of comments.

  1. Single line comment
  2. Multi line comment

Single line comments

Single line are commented as shown below.

# This is a single line comment
print("hello world!")

Multi line comments

Multiple lines are commented as follows.

"""This is a
multi line
comment"""
print("hello world!")

Now, as we are familiar with the basic python syntax we will go ahead and learn how to declare variables in python.

Leave a Reply

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

%d bloggers like this: