Python Basic Syntax

In the previous tutorial, we have seen a very basic python program that uses a print statement.  Before we move further into programming, we will see the Python basic syntax rules in this tutorial.

What is a syntax for any programming language?

In programming, syntax refers to the rules that specify the correct combined sequence of symbols that can be used to form a correctly structured program using a programming language. Programmers communicate with computers through the correctly structured syntax, semantics, and grammar of a programming language.

Python Basic Syntax Rules

1. Case sensitive

Hence the variables ‘test’ and ‘Test’ are not the same.

test=1
Test='a'
print(test,Test)

2. Comments

Before writing a new piece of code, its a best practice to write a line or two(comments) describing what the code does. A single-line comment begins with a hash character(#) which is not a part of the string literal and ends at the end of the physical line. All characters after the # character up to the end of the line are part of the comment and the Python interpreter ignores them.

# This is a comment

3. Python Docstrings

A docstring is similar to comments but unlike comments, they are more specific. Also, they are retained at runtime. This way, the programmer can inspect them at runtime.  A docstring starts and ends with three single/double-quotes.

"""
Name of the module:
Author of the module:
Time at which the module was created:
"""

4. Python Multiline Statements

Python does not mandate semicolons. A new line means a new statement. But sometimes, you may want to split a statement over two or more lines for readability. We can achieve this by:
a. backslash \ at the end of each line to explicitly denote line continuation.

var='hi\
how are\
you'
print(var)

b. Triple quotes ”” or “””

var='''hi
how are
you'''
print(var)

5. Indentation

Python provides no braces to indicate blocks of code for class and function definitions or flow control. Blocks of code are denoted by line indentation, which is rigidly enforced. The number of whitespaces (spaces and tabs) in the indentation is not fixed, but all statements within the block must be the indented same amount

if True:
  print("YES")

True is a reserved keyword in python

Between ‘if’ and ‘print’ statement you might have noticed a tab or 4 spaces gap, that is indentation.

Below is an example of an indentation error.

if True:
print("YES")

6. Variables

In Python, you don’t define the type of the variable. It is assumed on the basis of the value it holds.

a=10
print(type(a))
a='10'
print(type(a))

Conclusion

The above-given syntax rules are very basic. Don’t worry if you are confused about indentation and all, as we progress into loops in python, we will be seeing more examples of indentation. We have a separate topic on strings in the upcoming tutorial, to know more about single, double and triple quotes

Reference

Reference 1

Translate »