Python Syntax

Python is a High-Level Programming language created and introduced by Guido Van Rossum back in 1991. It is one of the most popular programming languages in the world. Python aims to make coding easier and more friendly for beginners. That is why Python code is generally more readable than other programming languages. Python programming doesn't follow any hard fast rule like other languages, such as a line does not need to end with a semicolon. The only thing to care about with Python code is it uses indentation to define a block of lines. Such features make Python user-friendly and easier to learn and understand.

Python Interactive Mode

We can run Python code using the Interactive mode. This mode is mostly used to test a small piece of code. To access the Python's Interactive Mode, run the given command in the terminal without any arguments: python.

			

The python command will open a Python Interpreter, which will interpret every single line of code immediately. For Example:
Python 3.10.2 (main, Jan 15 2022, 19:56:27) [GCC 11.1.0] on Linux
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello, How are you doing?")

				

Output:

Hello, How are you doing?

As we can see, each line of code we enter, the line is immediately executed by the Interpreter.

Python Script Mode

The Python Script Mode is used to execute a proper python code written in the form of a script. This mode can be accessed by providing the path of the python script as an argument to the python interpreter.

Example:

			

python my_script.py

				

Output:

Hello World!

Python Line Statements

In Python, each line is treated as a separate statement unless enclosed inside some parentheses. It is not compulsory to use ';' to terminate a line statement.

			

x = 10  #A line statement

print(x)    #A line statement

print(x+1)  #A line statement

				

Output:

10 11

To write multiline comment statements in the Python, "\" character is used. Put the \ at the end of each line part of the multiline statement.

			

x=10

print \
(\
   x*x\
   ) #multiline statement

				

Output:

100

Python Indentation

Python uses indentation to mark a block of statements. Unlike other languages like Java, C, and C++ that make use of brackets to mark a block of code. Therefore, the statements with the same indentation are treated as belonging to the same code block.

The indentation needs to be at least one space character. Generally, the tab key on the keyboard is used to indent a line of code. The tab key adds four space characters before the line of code.

			

x = 25

if x%5!=0:
   print("X is not divisible by 5")    # This is block of code

print("X is divisible by 5")    # This is block of code

				

Output:

X is divisible by 5

In the above example, the code inside the "if" block and the code outside the "if" block have different indentations. So, the "if" condition evaluates to false; therefore, the block's code is not executed. While the code after the "if" block is executed without any issue.

Indentation should be done properly in Python as it raises an error if the wrong indentation is performed in the code.

			

def my_function(x):
print(x)

				

Output:

IndentationError: expected an indented block after function definition on line 1

Python Identifiers

Identifiers are the names that are given to a variable in Python. Variables are the reserved memory blocks that can store a significant kind of value, and the value inside the variable can be modified if needed.

In Python, Variable creation can be done by simply typing the name of the variable(x, a, y, dd, etc.) followed by an '=' operator and then the desired value of the variable.

			

qty = 100

				

Output:

customer = 'John'

In the above code snippet, the names my_var and my_var2 are variable Identifiers.

In Python, there is no need to mention the data type while defining a variable explicitly. Python does that automatically when the value is assigned to a variable.

			

my_var = 5           #qty is an integer

print(type(my_var))

my_var = 'Python'    #my_var is now a string

print(type(my_var))

				

Output:

<class 'int'> <class 'str'>

Reserved Keywords in Python

These are reserved words that convey a special meaning to the Interpreter. Keywords are part of the syntax and cannot be used as identifiers. There are many keywords available in Python. These are given below.

Available Keywords in Python

Python has the following list of keywords that can't be used as a variable name or argument name, etc. Using reserved keywords may cause errors in the code.

False await else import pass
None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield

Python Parenthesis

Different parentheses used in different situations differ in their meaning in Python.

The list is denoted by a [] parentheses in Python. Example:

			

my_list = [1,2,3,4,5] #creating a list

print(my_list)

				

Output:

[1, 2, 3, 4, 5]

The tuple is denoted by a ( ) parentheses. Example:

			

# Creating a tuple(Homogeneous Elements)
my_tuple = ('t','u','p','l','e')
# Creating a tuple(Heterogeneous Elements)
my_tuple2 = (1, 'Tuple', 2, 3, 4, 5)

print(my_tuple)
print(my_tuple2)

				

Output:

('t', 'u', 'p', 'l', 'e') (1, 'Tuple', 2, 3, 4, 5)

But if () parentheses are used in an expression, then the part inside the parentheses is evaluated first. It is similar to the BODMAS rule in Mathematics.

			

print( (5*4)/2 )

				

Output:

10.0

The Dictionary object is denoted by { } parentheses.

			

my_dict = {"Mercury":1, "Venus":2, "Earth":3, "Mars":4}

print(my_dict)

				

Output:

{'Mercury': 1, 'Venus': 2, 'Earth': 3, 'Mars': 4}

Python Comments

Comments are text inside the program, helpful in the documentation, and ignored by the Interpreter while programming execution. The programmer uses comments to write the description of the functionality of that particular piece of code. Writing comments is an excellent practice while working on big projects.

In Python, we use the # character before a line of text to mark it as a comment.

			

x = 49

if x%7!=0:
   print("X is not divisible by 7")    # This is block of code

print("X is divisible by 7")    # This is block of code

				

Output:

X is divisible by 7

As we can see, the text starting with the # character is a comment in the code.

Python Quotations

Quotations are used to denote Strings. The string is a collection of more than one character inside quotation marks. Strings are usually used to store text data. Python Strings are immutable (can't be changed).

			

my_var = 'hello'    #String Literal using single quotes
#or
my_var = "hello"    #String Literal using double quotes

				

The main difference between declaring a string literal using a single or double quote is that in single quotes, double quotes are allowed inside the single quotes.

For Example, with single quotes, you can write something like this.

			

var_message = 'John greeted me by saying, "Hi! What's up?"'
print(var_message)

				

Output:

John greeted me by saying, "Hi! What's up?"

If you use double quotes instead.

			

var_message = "John greeted me by saying "Hi! What's up?""
print(var_message)

				

Output:

SyntaxError: invalid syntax

To use the single and double quotes in a string, use the triple quotes.

			

var_message = '''
John greeted me by saying.'
"Hi! What's up?"
'''
print(var_message)
	

				

Output:

'John greeted me by saying.' "Hi! What's up?"

As you can see in the above example, we can also use triple quotes to write multiline string literals.

While writing multiline strings in the code, the output needs to be in a single line. Use "\" at the end of each line.

			

var_message = '''\
'John greeted me by saying \
"Hi! What's up?"'\
'''
print(var_message)

				

Output:

'John greeted me by saying, "Hi! What's up?"' "\" also works with single quotes and double quotes.