Syntax and Symantics#

After installing Python, basics thing to understand is about syntax and semantics of Python.

Hello, World!#


Let’s create a very simple program called Hello World. This simple statement will print Hello, World! on the screen.

Keywords#


Keywords are the reserved words in Python.

  1. We cannot use a keyword as a variable name, function name or any other identifier.

  2. In Python, keywords are case sensitive.

All the keywords except True, False and None are in lowercase and they must be written as they are. The list of all the keywords is given below.

Keywords in Python

False

break

for

not

None

class

from

or

True

continue

global

pass

__peg_parser__

def

if

raise

and

del

import

return

as

elif

in

try

assert

else

is

while

async

except

lambda

with

await

finally

nonlocal

yield

for = 6 # It will give error becasue "for" is keyword and we cannot use as a variable name.
  Cell In[3], line 1
    for = 6 # It will give error becasue "for" is keyword and we cannot use as a variable name.
        ^
SyntaxError: invalid syntax

Identifiers#


An identifier is a name given to entities like class, functions, variables, etc. It helps to differentiate one entity from another.

Rules for writing identifiers#

  1. Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an underscore _.

  2. An identifier cannot start with a digit. 1variable is invalid, but variable1 is perfectly fine.

  3. Keywords cannot be used as identifiers

        global = 3 # because "global" is a keyword
            ^
        SyntaxError: invalid syntax
  1. We cannot use special symbols like !, @, #, $, % , etc. in our identifier.

        m@ = 3
        ^
        SyntaxError: invalid syntax

Indentation#


No spaces or tab characters allowed at the start of a statement: Indentation plays a special role in Python.

indentation

Most of the programming languages like C, C++, and Java use braces { } to define a block of code. Python, however, uses indentation.

A comparison of C & Python will help you understand it better.

indentation

Comments#


Comments are used to add notes to your code. Comments are ignored by the Python interpreter.

Single-line comments#

Single-line comments start with # and end with the end of the line.

# This is single line comment

Multi-line comments#

Multi-line comments start with ''' and end with '''.

# This is multi line comment
# This is multi line comment
# This is multi line comment
''' 
This is multi line comment
This is multi line comment 
'''

Docstrings#

A docstring is short for documentation string.

Triple quotes are used while writing docstrings. For example:

>>>def double(num):
>>>    """Function to double the value"""
>>>    return 3*num

Docstrings appear right after the definition of a function, class, or a module.

The docstrings are associated with the object as their __doc__ attribute.

So, we can access the docstrings of the above function with the following lines of code:

Variables#


A variable is a named location used to store data in the memory. It is helpful to think of variables as a container that holds data that can be changed later in the program.

Data types#


Every value in Python has a datatype. Since everything is an object in Python programming, data types are actually classes and variables are instance (object) of these classes.

Numbers#

  • Integers

  • Floating point numbers

  • Complex numbers

a = 6
print(a, "is of type", type(a))
print(a, "is integer number?", isinstance(5,int))

a = 3.0
print(a, "is of type", type(a))
print(a, "is float number?", isinstance(2.0,float))

a = 1+2j  # '1' is real part and '2j' is imaginary part
print(a, "is of type", type(a))
print(a, "is complex number?", isinstance(1+2j,complex))
6 is of type <class 'int'>
6 is integer number? True
3.0 is of type <class 'float'>
3.0 is float number? True
(1+2j) is of type <class 'complex'>
(1+2j) is complex number? True

List [ ]#

List is an ordered sequence of items.

  • All the items in a list do not need to be of the same type

  • Can also include duplicate items.

  • List is mutable. We can add, remove or modify items in the list.

>>>a = [1, 3.3, 'python']

We can use the slicing operator [ ] to extract an item or a range of items from a list. The index starts from 0 in Python.

x = [6, 99, 77, 'Apple']
print(x, "is of type", type(x))
[6, 99, 77, 'Apple'] is of type <class 'list'>

Example

a = [5, 10, 15, 20, 25, 30, 35, 40]  # Total elemnets is 8
#   [0   1   2   3   4   5   6   7]  ⬅ Index forward
#   [-8 -7  -6  -5  -4  -3  -2  -1]  ➡ Index backward

# index '0' is element '1' = 5,
# index '1' is element '2' = 10,
# index '2' is element '3' = 15,
# .
# .
# .
# index '7' is element '8' = 40,

a[1] # To access the elements in the list
    
# a[2] = 15
print("a[2] = ", a[2])

# a[0:3] = [5, 10, 15]
print("a[0:3] = ", a[0:3])  # [0:3] means elements from 0 uptil 2 index (not include last element)
                            # [0:3] means from index 0 to 3 - 1 
                            # [0:3] means from index 0 to 2
    
# a[5:] = [30, 35, 40]  # [5:] means all the elements from 5 till end
print("a[5:] = ", a[5:])

# a[5:-2] = [30] #[5:-2] means all the elements from 5 till second last
print(f"a[5:-2] = {a[5:-2]}")
a[2] =  15
a[0:3] =  [5, 10, 15]
a[5:] =  [30, 35, 40]
a[5:-2] = [30]

Tuple ( )#

  • Tuple is an ordered sequence of items same as a list.

  • Tuples are immutable. Tuples once created cannot be modified.

Tuples are used to write-protect data and are usually faster than lists as they cannot change dynamically.

It is defined within parentheses () where items are separated by commas.

>>>t = (6,'program', 1+3j)
# Tuple 't' have 3 elements
t = (6,'program', 1+3j) 
#   (0        1      2) ➡ Index forward

# index '0' is element '1'= 6 
# index '1' is element '2'= program
# index '2' is elemtnt '3'= 1+3j

# t[1] = 'program'
print("t[1] = ", t[1])

# t[0:3] = (6, 'program', (1+3j))
print("t[0:3] = ", t[0:3])

# Generates error
# Tuples are immutable
t[0] = 10  # trying to change element 0 from '6' to '10' will throw error
t[1] =  program
t[0:3] =  (6, 'program', (1+3j))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[13], line 17
     13 print("t[0:3] = ", t[0:3])
     15 # Generates error
     16 # Tuples are immutable
---> 17 t[0] = 10  # trying to change element 0 from '6' to '10' will throw error

TypeError: 'tuple' object does not support item assignment

Strings#

String is sequence of Unicode characters. We can use single quotes or double quotes to represent strings.

Multi-line strings can be denoted using triple quotes, ''' or """.

s = "This is a string"  # s is my variable
print(s)
s = '''A multiline
string'''
print(s)
This is a string
A multiline
string

Just like a list and tuple, the slicing operator [ ] can be used with strings. Strings, however, are immutable.

s = 'Hello world!' # total 12 elements. Index start from '0' to '11'

# s[4] = 'o'
print("s[4] = ", s[4])

# s[6:11] = 'world' # index '6' to '11' means element from 6 to 10
print("s[6:11] = ", s[6:11])
s[4] =  o
s[6:11] =  world

Set { }#

  1. Set is an unordered collection of unique items.

  2. Set is defined by values separated by comma inside braces { }.

  3. Items in a set are not ordered.

a = {7,1,3,6,9}

# printing set variable
print("a = ", a)

# data type of variable a
print(type(a))
a =  {1, 3, 6, 7, 9}
<class 'set'>

We can perform set operations like union, intersection on two sets. Sets have unique values. They eliminate duplicates.

a = {1,2,2,3,3,3} # we can see total 6 elements 
print(a)
{1, 2, 3}

Since, set are unordered collection, indexing has no meaning. Hence, the slicing operator [] does not work.

a = {1,2,3}  # in Set data type we cannot access the elements because set is unordered collection
a[1]  # Index [1] means element 2
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[19], line 2
      1 a = {1,2,3}  # in Set data type we cannot access the elements because set is unordered collection
----> 2 a[1]  # Index [1] means element 2

TypeError: 'set' object is not subscriptable

Dictionary { }#

  1. Dictionary is an unordered collection of key-value pairs.

  2. It is generally used when we have a huge amount of data. Dictionaries are optimized for retrieving data. We must know the key to retrieve the value.

  3. In Python, dictionaries are defined within braces {} with each item being a pair in the form key:value. Key and value can be of any type.

d = {1: 'Apple', 2: 'Cat', 3: 'Food'}  # 'Apple' is element and 1 is the key of element.
print(d, type(d))

d[3]
{1: 'Apple', 2: 'Cat', 3: 'Food'} <class 'dict'>
'Food'

Operators#


Operators are special symbols in Python that carry out arithmetic or logical computation. The value that the operator operates on is called the operand.

Arithmatic#

Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication etc.

Symbol

Task Performed

Meaning

Example

+

Addition

add two operands or unary plus

x + y or +2

-

Subtraction

substract right operand from the left or unary minus

x - y or -2

*

Multiplication

Multiply two operands

x * y

/

Division

Divide left operand by the right one (always results into float)

x / y

%

Modulus (remainder)

remainder of the division of left operand by the right

x % y (remainder of x/y)

//

Integer/Floor division

division that results into whole number adjusted to the left in the number line

x // y

**

Exponentiation (power)

left operand raised to the power of right

x ** y (x to the power y)

Comparison/Relational#

Comparison operators are used to compare values. It either returns True or False according to the condition.

Symbol

Task Performed

Meaning

Example

>

greater than

True if left operand is greater than the right

x > y

<

less than

True if left operand is less than the right

x < y

==

equal to

True if both operands are equal

x == y

!=

not equal to

True if both operands are not equal

x != y

>=

greater than or equal to

True if left operand is greater than or equal to the right

x >= y

<=

less than or equal to

True if left operand is less than or equal to the right

x <= y

Logical/Boolean#

Logical operators are the and, or, not operators.

Symbol

Meaning

Example

and

True if both the operands are true

x and y

or

True if either of the operand is true

x or y

not

True if operand are false (complements the operand)

not x

Bitwise#

Bitwise operators act on operands as if they were string of binary digits. It operates bit by bit, hence the name.

For example: 2 is 10 in binary and 7 is 111.

In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)

Operator

Meaning

Symbol

Task Performed

Example

and

Logical and

&

Bitwise And

x & y = 0 (0000 0000)

or

Logical or

\(\mid\)

Bitwise OR

x | y = 14 (0000 1110)

not

Not

~

Bitwise NOT

~x = -11 (1111 0101)

 

 

^

Bitwise XOR

x ^ y = 14 (0000 1110)

 

 

>>

Bitwise right shift

x >> 2 = 2 (0000 0010)

 

 

<<

Bitwise left shift

x << 2 = 40 (0010 1000)

Assignment#

Assignment operators are used in Python to assign values to variables.

a = 5 is a simple assignment operator that assigns the value 5 on the right to the variable a on the left.

There are various compound operators in Python like a += 5 that adds to the variable and later assigns the same. It is equivalent to a = a + 5.

Symbol

Example

Equivalent to

=

x = 5

x = 5

+=

x += 5

x = x + 5

-=

x -= 5

x = x - 5

*=

x *= 5

x = x * 5

/=

x /= 5

x = x / 5

%=

x %= 5

x = x % 5

//=

x //= 5

x = x // 5

**=

x **= 5

x = x ** 5

&=

x &= 5

x = x & 5

|=

x |= 5

x = x | 5

^=

x ^= 5

x = x ^ 5

>>=

x >>= 5

x = x >> 5

<<=

x <<= 5

x = x << 5

Special operators#

Python language offers some special types of operators like the identity operator or the membership operator.

Symbol

Meaning

Example

is

True if the operands are identical (refer to the same object)

x is True

is not

True if the operands are not identical (do not refer to the same object)

x is not True

in

True if value/variable is found in sequence

5 in x

not in

True if value/variable is not found in sequence

5 not in x

Namespaces & Scope#


What is Name in Python?

Name (also called identifier) is simply a name given to objects. Everything in Python is an object. Name is a way to access the underlying object.

For example, when we do the assignment a = 2, 2 is an object stored in memory and a is the name we associate it with.

# Note: You may get different values for the id

a = 2
print('id(a) =', id(a))

a = a+1
print('id(a) =', id(a))

print('id(3) =', id(3))

b = 2
print('id(b) =', id(b))
print('id(2) =', id(2))
id(a) = 4334066392
id(a) = 4334066424
id(3) = 4334066424
id(b) = 4334066392
id(2) = 4334066392

What is happening in the above sequence of steps? Let’s use a diagram to explain this:

Memory diagram of variables in Python:

../../_images/ns1.png
  • Initially, an object 2 is created and the name a is associated with it,

  • When we do a = a+1, a new object 3 is created and now a is associated with this object.

    Note that id(a) and id(3) have the same values.

  • Furthermore, when b = 2 is executed, the new name b gets associated with the previous object 2.

Namespace#

Namespace is a collection of names.

In Python, you can imagine a namespace as a mapping of every name you have defined to corresponding objects.

Different namespaces can co-exist at a given time but are completely isolated.

A namespace containing all the built-in names is created when we start the Python interpreter and exists as long as the interpreter runs.

This is the reason that built-in functions like id(), print() etc. are always available to us from any part of the program. Each module creates its own global namespace.

These different namespaces are isolated. Hence, the same name that may exist in different modules do not collide.

Modules can have various functions and classes. A local namespace is created when a function is called, which has all the names defined in it. Similar, is the case with class. Following diagram may help to clarify this concept.

<img src=“images/ns2.png” width=“300” alt=”namespace/>

Variable Scope#

A scope is the portion of a program from where a namespace can be accessed directly without any prefix.

At any given moment, there are at least three nested scopes.

  1. Scope of the current function which has local names

  2. Scope of the module which has global names

  3. Outermost scope which has built-in names

When a reference is made inside a function, the name is searched in the local namespace, then in the global namespace and finally in the built-in namespace.

If there is a function inside another function, a new scope is nested inside the local scope.

Example of Scope and Namespace in Python

>>>def outer_function():
>>>    b = 30
>>>    def inner_func():
>>>        c = 60

>>>a = 90

Here,

  1. the variable a is in the global namespace.

  2. Variable b is in the local namespace of outer_function() and

  3. c is in the nested local namespace of inner_function().

  • c is local to inner_function()

  • b is nonlocal and a is global.

We can read as well as assign new values to c but can only read b and a from inner_function().

If we try to assign as a value to b, a new variable b is created in the local namespace which is different than the nonlocal b. The same thing happens when we assign a value to a.

However, if we declare a as global, all the reference and assignment go to the global a.

Similarly, if we want to rebind the variable b, it must be declared as nonlocal. The following example will further clarify this.

def outer_function():
    a = 30

    def inner_function():
        a = 60
        print('a =', a)

    inner_function()
    print('a =', a)


a = 90
outer_function()
print('a =', a)
a = 60
a = 30
a = 90

Control flow#


The flow control statements are divided into three categories:

  1. Conditional statements

  2. Iterative statements

  3. Transfer/Control statements

<img src=“images/fcs.png” width=“500” alt=”control-flow/>

If statement#

Syntax

if(condition):
   statement 1
   statement 2
   statement n
if-statement
# Example: If the number is positive, we print an appropriate message

num = 3
if (num > 0):  # if condition is TRUE: enter the body of if
    print(num, "is a positive number.")
print("This is always printed.")

num = -1
if num > 0:  # if condition is FALSE: do not enter the body of if
    print(num, "is a negative number.")
print("This is also always printed.")
3 is a positive number.
This is always printed.
This is also always printed.

If-else statement#

Syntax

if condition:
   statement 1
else:
   statement 2
../../_images/ife0.png
x = 1

if x > 3:
    print ("Case 1")
if x <= 3:
    print ("Case 2")
Case 2

If-elif-else statement#

Syntax

if condition-1:  
    statement 1 
elif condition-2:
    stetement 2 
elif condition-3:
    stetement 3 
    ...         
else:            
    statement  
if-elif-else
# Example:

'''In this program, we check if the number is positive or negative or zero and 
display an appropriate message'''

num = 0

# Try these two variations as well:
# num = 0
# num = -4.5

if num > 0:
    print("Positive number")
elif num == 0:
    print("Zero")
else:
    print("Negative number")
Zero

Nested if statement#

Syntax

if condition1:
    if condition2:
        statement
    else:
        statement
else:
    statement
# Example 1:

a=10
if a>=20:  # Condition FALSE
    print ("Condition is True")
else:  # Code will go to ELSE body
    if a>=15:  # Condition FALSE
        print ("Checking second value")
    else:  # Code will go to ELSE body
        print ("All Conditions are false")
All Conditions are false

For loop#

Syntax

for element in sequence:
   body of for loop 
  1. First, element is the variable that takes the value of the item inside the sequence on each iteration.

  2. Second, all the statements in the body of the for loop are executed with the same value. The body of for loop is separated from the rest of the code using indentation.

  3. Finally, loop continues until we reach the last item in the sequence. The body of for loop is separated from the rest of the code using indentation.

../../_images/for0.png
# Example 1: For loop 

words = ['one', 'two', 'three', 'four', 'five']

for i in words:
    print(i)
one
two
three
four
five

For loop with range()#

The range() function returns a sequence of numbers starting from 0 (by default) if the initial limit is not specified and it increments by 1 (by default) until a final limit is reached.

The range() function is used with a loop to specify the range (how many times) the code block will be executed.

We can generate a sequence of numbers using range() function. range(5) will generate numbers from 0 to 4 (5 numbers).

for-loop

We can also define the start, stop and step size as range(start, stop,step_size). step_size defaults to 1 if not provided.

# Example 1: How range works in Python?

# empty range
print(list(range(0)))

# using range(stop)
print(list(range(10)))

# using range(start, stop)
print(list(range(1, 10)))
[]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
# Example 2:

for i in range (2, 12, 2):  # beginning 2 with distance of 2 and stop before 12
    print (i)
2
4
6
8
10

For loop with list#

# Example: Iterate over a list Method 1

numbers = [1, 2, 3, 6, 9]
for num in numbers:
    print(num)
1
2
3
6
9

For loop with tuple#

# Example 1: For loop with tuple

numbers = (0, 1, 2, 3, 4, 5)
for number in numbers:
    print(number)
0
1
2
3
4
5

For loop with dictionary#

# Example 1: Iterting only keys

dict1 = {"Antibiotics": "Penicillin", "Inventor": "Fleming", "Year": 1928}
for key in dict1:
    print(key)
Antibiotics
Inventor
Year
# Example 2: For loop with dictionary
#Looping through a dictionary gives you the key of the dictionary.

person = {
    'first_name':'Anukool',
    'last_name':'chaturvedi',
    'age':1000,
    'country':'Finland',
    'is_marred':True,
    'skills':['Python', 'Matlab', 'R', 'C', 'C++'],
    'address':{
        'street':'Space street',
        'zipcode':'02210'
    }
}
for key in person:
    print(key)
print('\n')
for key, value in person.items():
    print(key, value) # this way we get both keys and values printed out
first_name
last_name
age
country
is_marred
skills
address


first_name Anukool
last_name chaturvedi
age 1000
country Finland
is_marred True
skills ['Python', 'Matlab', 'R', 'C', 'C++']
address {'street': 'Space street', 'zipcode': '02210'}

For loop with set#

# Example 6: For loop with set

mix_fruits = {'Banana', 'Apple', 'Mango', 'Orange', 'Guava', 'Kiwi', 'Grape','Apple'}
for fruits in mix_fruits:
    print(fruits)
Apple
Kiwi
Guava
Mango
Grape
Orange
Banana

List comprehension#

Syntax

[expression for item in iterable]

List comprehension is an elegant and concise way to create lists. List comprehension is considerably faster than processing a list using the for loop.

  1. The expression is executed for each item in the iterable.

  2. The item is the variable that takes the value of the item inside the iterable on each iteration.

  3. The iterable is the sequence that the expression is executed on.

# Example: Print the even numbers by adding 1 to the odd numbers in the list

odd = [1, 5, 7, 9]
even = [i + 1 for i in odd if i % 2 == 1]
print(even)
[2, 6, 8, 10]

While loop#

The while loop in Python is used to iterate over a block of code as long as the expression/condition is True. When the condition becomes False, execution comes out of the loop immediately, and the first statement after the while loop is executed.

We generally use this loop when we don’t know the number of times to iterate beforehand.

Python interprets any non-zero value as True. None and 0 are interpreted as False.

Syntax

while condition:
   body of while loop
  1. In the while loop, expression/condition is checked first.

  2. The body of the loop is entered only if the expression/condition evaluates to True.

  3. After one iteration, the expression/condition is checked again. This process continues until the test_expression evaluates to False.

../../_images/wh0.png

Note: An infinite loop occurs when a program keeps executing within one loop, never leaving it. To exit out of infinite loops on the command line, press CTRL + C.

# Example 1: Print numbers less than 5

count = 1
# run loop till count is less than 5
while count < 5:
    print(count)
    count = count + 1
1
2
3
4

Control statements#

Loops in Python are used to iterate repeatedly over a block of code. But at times, you might want to shift the control once a particular condition is satisfied.

Control statements in python are used to control the flow of execution of the program based on the specified conditions. Python supports 3 types of control statements:

Statement

Description

1

break

Terminate the current loop. Use the break statement to come out of the loop instantly.

2

continue

Skip the current iteration of a loop and move to the next iteration

3

pass

Do nothing. Ignore the condition in which it occurred and proceed to run the program as usual

The break and continue statements are part of a control flow statements that helps you to understand the basics of Python.

control-state

Break#

break statement provides you with the opportunity to exit out of a loop when an external condition is triggered, and the program control transfer to the next statement following the loop.

If the break statement is inside a nested loop (loop inside another loop), the break statement will terminate the innermost loop.

You’ll put the break statement within the block of code under your loop statement.

break

The working of break statement in for loop and while loop is shown below.

break1
# Example 1:

for i in range(100):
    print(i,end="...")
    if i>=10:
        break
print("completed.")
0...1...2...3...4...5...6...7...8...9...10...completed.
# Example 2: program to check if letter 'A' is present in the input

a = input ("Enter a word: ")
for i in a:
    if (i == 'A'):
        print ("A is found")
        break 
else:
    print ("A not found")
    
# Note: Python is case-sensitive language.
A not found

Continue#

In Python, the continue statement is a jump statement which is used to skip execution of current iteration. After skipping, loop continue with next iteration. We can use continue statement only with for loop as well as while loop in Python.

continue

The working of continue statement in for loop and while loop is shown below.

<img src=“images/con2.png” width=“700” alt=”continue1/>

# Example 1: use the `continue` statement inside a `while` loop

name = 'Art hu r'

size = len(name)
i = -1
# iterate loop till the last character
while i < size - 1:
    i = i + 1
    # skip loop body if current character is space
    if name[i].isspace():
        continue
    # print current character
    print(name[i], end=' ')
A r t h u r 
# Example 2:

count = 0
while count < 10:
    count += 1
    if count % 2 == 0: # even number
        count += 2
        continue
    elif 5 < count < 9:
        break # abnormal exit if we get here!
    print("count =",count)
else: # while-else
    print("Normal exit with",count)
count = 1
count = 5
count = 9
Normal exit with 12

Pass#

pass keyword is used to execute nothing; it means, when we don’t want to execute code, the pass can be used to execute empty.

It is used as a placeholder for future implementation of functions, loops, etc.

Suppose we have a loop or a function that is not implemented yet, but we want to implement it in the future. They cannot have an empty body. The interpreter would give an error. So, we use the pass statement to construct a body that does nothing.

Example:#

'''pass is just a placeholder for
functionality to be added later.'''
>>> sequence = {'p', 'a', 's', 's'}
>>> for val in sequence:
>>>     pass

We can do the same thing in an empty function or class as well.

>>> def function(args):
>>>     pass

or

>>> class Example:
>>>    pass
# Example 1:

months = ['January', 'June', 'March', 'April']
for mon in months:
    pass
print(months)
['January', 'June', 'March', 'April']