Python Syntax and Indentation Explained for Beginners (with Examples)

Python Syntax and Indentation(With Examples)

Python is know for its simple and readable syntax as it is as similar as reading English. However, beginners often get confused about syntax rules and indentation.

In this blog, we will clearly understand Python syntax, indentation, comments and common mistakes with easy examples.

This post is a must-read before writing real Python programs.

What is Python Syntax?

Python syntax refers to the rules and structure used to write Python code correctly.

Python is different from other languages because:

  • It does not use curly braces{} in its' code
  • It uses indentation (spaces) to define blocks of code
For example,

code:

#code to print hello CodingNotesHub

print("hello, CodingNotesHub!")

Now, As we have written our first code, lets' look into indentation.

What is indentation in Python?

Indentation means spaces at the beginning of a line. It defines a block of code. It uses 4 spaces indentation. Indentation is requires in conditional statements, loops, functions, classes. For example:

code 1 :

if age > 18:
    print("Adult")

Above code is correct indentation example, it's showing that print statement is inside the if block.

Also, avoid write the code as below as it will show an "IndentationError :expected an indented block":

code 2 :

if age > 18:
print("Adult")

Comments in Python

Comments in python are used to provide explanatory notes within the code that are not executed or interpreted by the computer. These are the additional readable information to clarify the source code. When the python interpreter encounters a comment, it ignores  it and move to the next line. Comments are only used for human readability only and are not executed by python interpreter. Therefore, they have no impact on the performance of the program

Types of Comments

Single-line comments are the comments written in single. It begins with hash symbol (#) and continue till the end of the line. Anything written after the hash symbol are considered as comment and are ignored by python interpreter.

For example,

code 3 :

#This is a comment
print("Python")

Multi-line Comments

Multi-line comments are the comments used to write comment in two or more lines. We can write multi-line comments either as triple-quoted string ("""------""") or using multiple hash symbols (#).

code 4:

"""
This is a multi-line
comment in Python
"""


Conclusion 

Python syntax is simple, but indentation is mandatory.
Once you understand indentation, writing Python programs becomes easy and enjoyable.

In the next blog, we will learn about  Variables and Data types in Python.







Comments

Popular posts from this blog

Python Input and Output(input() & print())

Python Conditional Statements(if, elif, else)

Introduction To Database Management System