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:

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:

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" + \

       "Chohan"

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"

print(name)

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:-

Numbers

 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

print(type(x))

print(type(y))

print(type(z))

Output:

<class 'int'>

<class 'int'>

<class 'int'>

Float

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

x = 35e3

y = 12E4

z = -87.7e100

print(type(x))

print(type(y))

print(type(z))

Output:-

<class 'float'>

<class 'float'>

<class 'float'>

Complex 

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

For Example:

num = 1 + 2j

print(type(num))

Output:-

<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:

print(a)

print(b)

print(c)

print(type(a))

print(type(b))

print(type(c))

Output

1.0

2

(1+0j)

<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'))

Output:

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).

Parameters

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))

Output:

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())

Output

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.

Parameters

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())

Output

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];

random.shuffle(list)

print("Reshuffled list : '', list)

Output

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.

Parameters

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))

Output

Random Float uniform(5, 10) : 5.52615217015

Random Float uniform(7, 14) : 12.5326369199

String

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 )

Output

Ram

Shyam

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

Output:

he

o

hello Pythonhello Python

hello Python how are you

List

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]

list.append(25)

print("after Append = ",list)

Output:

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.

list=[2,3,4,5,2,3,2]

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

Output:

element 2 isoccurred : 3

index() Method:

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

list=[2,3,4,5,6,7,8]

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

Output:

index of 3 is 1

Insert() Method:

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

list=[2,3,4,5,6,7,8]

x=0,y=1

list.insert(x,y)

print(list)

Output:

[1,2,3,4,5,6,7,8]

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.

list=[2,3,4,5,6,7,8]

list.remove(8)

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

Output:

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']

list.pop()

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.

list=[2,3,5,9,6,4,1,7,8]

print(“Sorted List : ”,list.sort())

Output:Sorted List : [1,2,3,4,5,6,7]

Tuple

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 = ()

print(my_tuple)

Output:

()

# Tuple having integers

my_tuple = (1, 2, 3)

print(my_tuple)

Output:

(1, 2, 3)

# tuple with mixed data types

my_tuple = (1, "Hello", 3.4)

print(my_tuple)

Output:

(1, "Hello", 3.4)

 

Dictionary

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]);

print(d);

print(d.keys());

print(d.values());

Output

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

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}

add()

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

For Example:

set ={5,10,15,20}

print("Set = ", set)

set.add(25)

print("After Add = ",set)

Output :

Set = {5,10,15,20}

After Add = {5,10,15,20,25}

update()

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

For Example:

set ={5,10,15,20}

print("Set = ", set)

set.update([25,30,35])

print("After Add = ",set)

Output :

Set = {5,10,15,20}

After update = {5,10,15,20,25,30,35}

remove()

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)

set.remove(20)

print("After remove = ",set)

Output :

Set = {5,10,15,20}

After remove = {5,10,15}

discard()

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)

set.discard(20)

print("After discard= ",set)

Output :

Set = {5,10,15,20}

After discard = {5,10,15}

pop()

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)

set.pop()

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.

a=b+c-d

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

1.

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

power=a**b

#print results

print("Add : ",add)

print("Sub : ",sub)

print("Multi ",mul)

print("Div1: ",div1)

print("Div2: ",div2)

print("mod : ",mod)

print("Power : ",power)

Output:

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

print(x)

Output

15

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)

Output

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

x=True

y=False

print("X and Y",x and y)

print("X or Y",x or y)

print("Not of X",not x)

Output

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)

Output:-

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)

Output

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:

list=[1,2,3,4,5]

num=int("Enter your number = ")

print("the given number is present in list or not = ",(num in list))

Output:

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))

Output:

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))

Output:

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))

Output:

A and B not point same Object = True