04. Variable and Operators

Python Identifierse

An identifier is a name of a variable, function, class, module or any other object. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores and digits (0 to 9).

Python does not allow punctuation characters such as @, $, and % within identifiers. Python is a case sensitive programming language. Thus, Name and name are two different identifiers for python.

Here are basic rules of identifier naming convention:
  1. Class names start with an uppercase letter. All other identifiers start with a lowercase letter.
  2. Starting an identifier with a single leading underscore indicates that the identifier is private.
  3. Starting an identifier with two leading underscores indicates a strongly private identifier.
  4. If the identifier also ends with two trailing underscores, the identifier is a language-defined special name.

Reserved Words

Python has several reserve words. Reserved words are written in lower case.  You can not use reserve words as a variable or constant or any other identifier name.  Here is the list of reserved words:

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

Block of statements

Unlike other languages like C/C++/Java, Python does not provide any special charter to indicate a block of code. You usually write blocks when you implement control statements.

Python specifies block of code by line indentation. All the lines with same indentation belong to same block. Number of spaces in the indentation is variable, but all statements within the block must be indented with same number of spaces.

For example:
price = 99
if (price < 100):
print("I can not buy Pizza")
print("Feeling bad :(")
else :
print("I can buy Pizza")
print("Yu Yum :)")
However, the following block will generate an error:

if (price < 100):
print("I can not buy Pizza")
print("Feeling bad :(")
else :
print("I can buy Pizza")
print("Yum Yum :)")

Thus, all the continuous lines, indented with same number of spaces would form a block.

Multi-Line Statements

Statements in Python typically end with a new line. Python allows to define multiple line statements. Line continuation character (\)  is used to break a statement into multiple lines.

For example:
name = "Vijay" + \
       "Dinanth" + \

Statements contained within the [], {}, or () brackets do not need to use the line continuation character.
For example:
days = ['Monday', 'Tuesday', 'Wednesday',
        'Thursday', 'Friday']

Quotation in Python

Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as long as the same type of quote starts and ends the string.
The triple quotes are used to span the string across multiple lines.

For example, all the following are correct:

name = ‘SunilOS’
address = "212 President Tower"
location = """6/2 South Tukogunj,
Nehru Statue Indore”””

What are Variables ?

Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory.

Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables,you can store integers, decimals or characters in these variables.

For Example:

name = "Rays"

Output: Rays

The data stored in memory can be of many types. For example, a person age is stored as a numeric value and his or her address is stored as alphanumeric characters. Python has various standard data types that are used to define the operations possible on them and the storage method for each of them.

Python has Five Standard Data Types:-


 Number data types store numeric values. Number objects are created when you assign a value to them

 Int :

Integer is a whole number,positive or negative, without decimals, of unlimited length.                    
For Example :
x = 2147483647
y = -32768
z = 9865879621477


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


Float, or "floating point number" is a number, positive or negative, containing one or more decimal.

x = 35e3
y = 12E4
z = -87.7e100

<class 'float'>
<class 'float'>
<class 'float'>


Complex numbers are written with a "j" as the imaginary part
For Example:

num = 1 + 2j

<class 'complex'>

Number Type Conversion

Python converts numbers internally in an expression containing mixed types to a common type for evaluation. But sometimes, you need to coerce a number explicitly from one type to another to satisfy the requirements of an operator or function parameter.

You can convert from one type to another with the int(), float(), and complex() methods:
For Example:
x = 1
y = 2.8
z = 1j
a = float(x) #convert from int to float:
b = int(y) #convert from float to int:
c = complex(x) #convert from int to complex:


<class 'float'>
<class 'int'>
<class 'complex'>

Random Number

Python does not have a random() function to make a random number, but Python has a built-in module called random that can be used to make random numbers:
Random numbers are used for games, simulations, testing, security, and privacy applications. Python includes following functions that are commonly used.

choice() Method:

The method choice() returns a random item from a list, tuple, or string.

Note − This function is not accessible directly, so we need to import random module and then we need to call this function using random static object.The following example shows the usage of choice() method.

import random
print("choice([1, 2, 3, 5, 9]) : ", random.choice([1, 2, 3, 5, 9]))
print("choice('A String') : ", random.choice('A String'))

choice([1, 2, 3, 5, 9]) : 2
choice('A String') : n

randrange() Method:

The method randrange() returns a randomly selected element from range(start, stop, step).


start − Start point of the range. This would be included in the range.
stop − Stop point of the range. This would be excluded from the range.
step − Steps to be added in a number to decide a random number.This method returns a random item from the given range

import random
print("randrange(100, 1000, 2) : ", random.randrange(100, 1000, 2))

randrange(100, 1000, 2) : 976

random() Method

The method random() returns a random float number between 0 to 1.

import random
# First random number
print("random() : ", random.random())
# Second random number
print("random() : ", random.random())

random() : 0.281954791393
random() : 0.309090465205

seed() Method

The method seed() sets the integer starting value used in generating random numbers. Call this function before calling any other random module function.
Note − This function is not accessible directly, so we need to import seed module and then we need to call this function using random static object.

x − This is the seed for the next random number. If omitted, then it takes system time to generate next random number.

For Example
import random
random.seed( 10 )
print("Random number with seed 10 : ", random.random())

Random number with seed 10 : 0.57140259469

shuffle() Method

The method shuffle() randomizes the items of a list in place.

import random
list = [20, 16, 10, 5];
print("Reshuffled list : '', list)

Reshuffled list : [16, 5, 10, 20]

uniform() Method

The method uniform() returns a random float r, such that x is less than or equal to r and r is less than y.
x − Sets the lower limit of the random float.
y − Sets the upper limit of the random float.
This method returns a floating point number.

import random
print("Random Float uniform(5, 10) : ", random.uniform(5, 10))
print("Random Float uniform(7, 14) : ", random.uniform(7, 14))

Random Float uniform(5, 10) : 5.52615217015
Random Float uniform(7, 14) : 12.5326369199


The string can be defined as the sequence of characters represented in the quotation marks. In python, we can use single, double, or triple quotes to define a string.
String handling in python is a straightforward task since there are various inbuilt functions and operators provided.

In the case of string handling, the operator + is used to concatenate two strings as the operation "hello"+" python" returns "hello python".
The operator * is known as repetition operator as the operation "Python " *2 returns "Python Python ".

Create string variables by enclosing characters in quotes.

For Example
first_name = 'Ram'
last_name = "Shyam"
print(first_name )
print(last_name )


Example Second
string1 = 'hello Python’ #string String1
string2 = ' how are you' #string string2

print (string1 [0:2]) #printing first two character using slice operator
print (string1 [4]) #printing 4th character of the string
print (string1 *2) #printing the string twice
print (string1 + string2 ) #printing the concatenation of str1 and str2

hello Pythonhello Python
hello Python how are you


List is set of element ,it contains heterogeneous element and list is mutable data type. it is also provide slicing operation.

list =[5,10,15,20]
print("list[2] = ", list[2])

Output :
list[2] = 15

List have multiple methods like

append() Method:

we can add more element by using append() method.

list =[5,10,15,20]
print("after Append = ",list)

after Append = [5,10,15,20,25]

count() Method:

count() method counts how many times an element has occurred in a list and returns it.

print(“element 2 isoccurred : ”,list.count(2))

element 2 isoccurred : 3

index() Method:

index() method finds the given element in a list and returns its position

print(“index of 3 is ”,list.index(3))

index of 3 is 1

Insert() Method:

The insert() method inserts an element to the list at a given index.



Note: where x is index number and y is inserted value.

remove() Method:

The remove() method searches for the given element in the list and removes the first matching element.

print(“After remove element list is : ”,list)

After remove element list is :[2,3,4,5,6,7]

Note: if given element not exist in list then remove method occurred error

pop() Method:

The pop() method removes the item at the given index from the list. The method also returns the removed item.

list = ['Python', 'Java', 'C++', 'French', 'C']
print(“after pop method list is : ”,list)
OutPut:after pop method list is : ['Python', 'Java', 'C++','French']

sort() Method:

The sort() method sorts the elements of a given list.

print(“Sorted List : ”,list.sort())
Output:Sorted List : [1,2,3,4,5,6,7]


A tuple is created by placing all the items (elements) inside parentheses(), separated by commas, and tuple is immutable . The parentheses are optional, however, it is a good practice to use them. A tuple can have any number of items and they may be of different types (integer, float, list, string, etc.).

For Example:
my_tuple = ()


# Tuple having integers
my_tuple = (1, 2, 3)

(1, 2, 3)

# tuple with mixed data types
my_tuple = (1, "Hello", 3.4)

(1, "Hello", 3.4)


Dictionary  is an unordered collection of key-value pairs.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.

For Example
d = {1:'Ram', 2:'Shyam', 3:'Vijay', 4:'Raju'};
print("1st name is "+d[1]);
print("2nd name is "+ d[4]);

1st name is Ram
2nd name is Shyam
{1:'Ram', 2:'Shyam', 3:'Vijay', 4:'Raju'}
dict_keys([1, 2, 3, 4])
dict_values(['Ram', 'Shyam', 'Vijay', 'Raju'])


set is a collection of element and duplicate elements are not allowed in set ,it contains heterogeneous element and set is mutable data type. it is not
provide slicing operation and it is unordered.

For Example
set ={5,10,15,20,5,15}
print("Set = ", set)

Output :
Set = {10,20,5,15}


we can add more element by using add() method.

For Example:
set ={5,10,15,20}

print("Set = ", set)
print("After Add = ",set)
Output :
Set = {5,10,15,20}
After Add = {5,10,15,20,25}


we can add multiple elements in set  by using update method.

For Example:
set ={5,10,15,20}

print("Set = ", set)
print("After Add = ",set)
Output :
Set = {5,10,15,20}
After update = {5,10,15,20,25,30,35}


we can remove set element using remove() method.but if element is not present in set then remove method will give error.

For Example:
set ={5,10,15,20}

print("Set = ", set)
print("After remove = ",set)
Output :
Set = {5,10,15,20}
After remove = {5,10,15}


we can remove set element  using discard() method.but if element is not present in set then discard method will not give error.

For Example:
set ={5,10,15,20}

print("Set = ", set)
print("After discard= ",set)
Output :
Set = {5,10,15,20}
After discard = {5,10,15}


we can remove set element  using pop() method.but set is contained  unordered element so you will not know which element is remove.

For Example:
set ={5,10,15,20}
print("Set = ", set)
print("After pop = ",set)
Output :
Set = {5,10,15,20}
After pop = {5,15,20}

What are Operators ?

Operators are special symbol symbol that perform specific operations on one,two or three operands,and then return a result. An operand refers to a variable ,object or a literal.

Above statement contains three operators +(plus), -(minus), and = (assignment). In
above statement a,b,c and d are called operands.

There are many types of operators in Python such as

1.Arithmetic operator
2.Assignment operator
3.comparison operator
4.Logical operator
5.Identity operator
6.Bitwise operator
7.Membership operator

Arithmetic Operator:

Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. Binary operators +(plus), - (minus),* (multiply), / (division),//(floor division),**(Exponent)

The only symbol that might look new to you is “%” , which divides one operand by another and return the remainder as its result. Here is an example expression that returns result
For Example:
a = 9
b = 4

# Addition of numbers
add = a + b

# Subtraction of numbers
sub = a - b

# Multiplication of number
mul = a * b

# Division(float) of number
div1 = a / b

# Division(floor) of number
div2 = a // b

# Modulo of both number
mod = a % b

#Exponent(Power) of number

#print results
print("Add : ",add)
print("Sub : ",sub)
print("Multi ",mul)
print("Div1: ",div1)
print("Div2: ",div2)
print("mod : ",mod)
print("Power : ",power)

Add : 13
Sub : 5
Multi 36
Div1: 2.25
Div2: 2
mod : 1
Power : 6561

Assignment operators:

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

For Example:
x = 5
x *= 3


Comparison operators:

These operators compare the values of two operands and return True or False based on condition. They are also called Relational operators.

== equal to
!= not equal to
> greater than
>= greater than or equal to
< less than
<= less than or equal to

For Example:
a = 100
b = 20
c = 100
print("A is greater Than B = ", a > b)
print("B is less than C = ",b < c)
print("A is not equal to C = ",a!=b)

A is greater Than B = True
B is less Than C = True
A is not equal to C = False

Logical operators:

Logical operators in Python are used for conditional statements are true or false. Logical operators in Python are AND, OR and NOT. For logical operators following conditions are applied.

AND operator – it returns True if both the operands are true
OR operator- it returns True if either of the operands is true
NOT operator- it returns True if operand is false

For Example
print("X and Y",x and y)
print("X or Y",x or y)
print("Not of X",not x)

X and Y False
X or Y True
Not of X False

Identity operators:

Identity operator compare the memory location of two objects, Identity Operators are used to check if two values (or variables) are located on the same part of the memory.

is Operator: It returns True if two variables point to the same object and false otherwise
is not Operator : It returns False if two variables point to the same object otherwise true otherwise

For Example :
num1 = 20
num2 = 20
num3 = 30
print("Is Operators = ",num1 is num2)
print("Is Not Operators = ",num1 is not num3)

Is Operators = True
Is Not Operators = True

Bitwise operators:

Bitwise operators are used to perform bit operations. All the decimal values will be converted into binary values

& (bitwise AND) if both bits are 1 then only 1 otherwise 0.
| (bitwise OR) if atleast one bit is 1 then 1 otherwise 0
^ (bitwise XOR) if both arguments are different then 1 otherwise 0
<< (left shift) bitwise left shift
>> (right shift) bitwise right shift
~ (bitwise NOT) Takes one number and inverts all bits of it

For Example:
# Binary of 60 =0011 1100
a = 60
# Binary of 13 = 0000 1101
b = 13
c = a & b;
Binary of 60 = 0011 1100
Binary of 13 = 0000 1101
12 = 0000 110 '''

print("Line 1 - Value of c is = ", c)

c = a | b # 61 = 0011 1101
print("Line 2 - Value of c is = ", c)

c = a ^ b # 49 = 0011 0001
print("Line 3 - Value of c is = ", c)

c = ~a; # -61 = 1100 0011
print("Line 4 - Value of c is = ", c)

c = a << 2 # 240 = 1111 0000
print("Line 5 - Value of c is = ", c)

c = a >> 2 # 15 = 0000 1111
print("Line 6 - Value of c is = ", c)

Line 1 - Value of c is = 12
Line 2 - Value of c is = 61
Line 3 - Value of c is = 49
Line 4 - Value of c is = -61
Line 5 - Value of c is = 240
Line 6 - Value of c is = 15

Membership Operators:

Python membership operators are used to check the membership of value inside a data structure. If the value is present in the data structure, then the resulting value is true otherwise it returns false.

in operator :
The ‘in’ operator is used to check if a value exists in a sequence or not. Evaluates to true if it finds a variable in the specified sequence and false otherwise.

For Example:
num=int("Enter your number = ")
print("the given number is present in list or not = ",(num in list))

Enter your number = 5
the given number is present in list or not = True

not in operator:
Evaluates to true if it does not find a variable in the specified sequence and false otherwise.

For Example:
a = 24
list = [10, 20, 30, 40, 50 ];
print("A is not present in list = ",(a not in list))

a is not present in list = True

is operator :
Evaluates to true if the variables on either side of the operator point to the same object and false otherwise.

For Example:
a = 5
b = 10
print("A and B point same Object = ",(a is b))

A and B point same Object = False

‘is not’ operator:
Evaluates to false if the variables on either side of the operator point to the same object and true otherwise.

For Example:
a = 5
b = 10
print("A and B not point same Object = ",(a is not b))

A and B not point same Object = True