UPDATED Data Science With Python Lab
UPDATED Data Science With Python Lab
Lab Manual
1. Arithmetic operators.
2. Relational or Comparision operators.
3. Equality operators.
4. Logical operators.
5. Bitwise operators.
6. Shift operators.
7. Assignment operators.
8. Ternary operator. (or) Conditional operator.
9. Special operators:
a. Identity operator.
b. Membership operator.
1. Arithmetic Operators:
The arithmetic operations are the basic mathematical operators which are used in our daily life. Mainly it
consists of seven operators.
i. Addition Operator :
Generally addition operator is used to perform the addition operation on two operands.
But in python we can use addition operator to perform the concatenation of strings, lists and so on, but
operands must of same datatype.
x = 2
y = 3
print("ADDITION RESULT : ", x + y)
ADDITION RESULT : 5
In [2]:
x = 2
y = 3.3
print("ADDITION RESULT : ", x + y) # both float and int type are accept
In [3]:
x = 2.7
y = 3.3
print("ADDITION RESULT : ", x + y) # both float type are accept
In [5]:
x = "2"
y = "3"
print("ADDITION RESULT : ", x + y) # concatenation will take place
ADDITION RESULT : 23
In [7]:
x = 2
y = bool(4.8)
print("ADDITION RESULT : ", x + y) #here bool(4.8) returns True i.e, 1
ADDITION RESULT : 3
In [9]:
x = "2"
y = str(bool(4.8))
print("ADDITION RESULT : ", x + y)
#bool returns 1 generally but we converted into str then it gives True
ADDITION RESULT : 2 True
In [10]:
x = "2"
y = str(complex(4.8)) #Here both strings so concatenation will take place
print("ADDITION RESULT : ", x + y)
ADDITION RESULT : 2(4.8+0j)
x = 2
y = complex(4.8)
print("ADDITION RESULT : ", x + y)
# here both are int type so addtion will take place
ADDITION RESULT : (6.8+0j)
Generally subtraction operator is used to perform the subtraction operation on two operands.
In [12]:
a = 30
b = 10
print("Subtraction result : ",a-b)
Subtraction result : 20
In [13]:
a = 30
b = "10"
print("Subtraction result : ",a-b)
--------------------------------------------------------------------------
a = 20
b = 10.00
print("Subtraction result : ",a-b)
In [16]:
a = 20
b = bool(10)
print("Subtraction result : ",a-b)
Subtraction result : 19
Generally multiplication operator is used to perform the multiplication operation on two operends
But in python we can use multiplication operator to perform the repetition of strings, lists and so on, but
operands must belongs to same datatype.
In [17]:
num1 = 23
num2 = 35
print("MULTIPLICATION RESULT : ",num1 * num2)
In [18]:
num1 = 23
num2 = 35.0
print("MULTIPLICATION RESULT : ",num1 * num2)
In [19]:
num1 = "23"
num2 = 5
print("MULTIPLICATION RESULT : ",num1 * num2) # 23 string will prints 5 times
Generally division operator is used to perform the division operation on two operands.
It returns the result in float type.
In [31]:
a = 3
b = 45
print("Division result : ", a/ b) # returns float value
In [32]:
a = 3
b = "45"
print("Division result : ", b / a)
a = 3
b = bool(0.0000)
print("Division result : ", a / b)
a = {1,2,3}
b = {1,2,3}
print("Division result : ", a / b)
v. Modulo Division:
It returns reminder.
In [40]:
a = 3
b = 4
print(a%b)
print(b%a)
3
1
vi. Floor Division:
Answer is 10
Answer is 11
In [41]:
print(10/2)
5.0
print(10/3)
3.3333333333333335
If you want to get integer value as result of division operation, you need to make use of floor division(//)
operator.
floor division(//) operator meant for integral arithmetic operations as well as floating point arithmetic
operations.
The result of floor division(//) operator can be always floor value of either integer value or float value
based on your arguments.
If both arguments are 'int' type, then the result is 'int' type.
If atleast one of the argument is float type, then the result is also float type.
In [43]:
print(10//2)
5
In [44]:
print(10/3)
3.3333333333333335
In [45]:
print(10.0/3)
3.3333333333333335
In [46]:
print(10.0//3)
3.0
In [47]:
print(10//3)
3
In [49]:
print(20/2)
print(20.5/2)
print(20//2)
print(20.5//2)
print(30//2)
print(30.0//2)
10.0
10.25
10
10.0
15
15.0
In [50]:
In [51]:
a = 10
b = 20
print('a < b is', a<b)
print('a <= b is', a<=b)
print('a > b is', a>b)
print('a >= b is', a>=b)
a < b is True
a <= b is True
a > b is False
a >= b is False
In [55]:
s1 = 'karthi'
s2 = 'karthi'
print(s1<s2)
print(s1<=s2)
print(s1>s2)
print(s1>=s2)
False
True
False
True
s1 = 'karthi'
s2 = 'Karthi'
print(s1<s2)
print(s1<=s2)
print(s1>s2)
print(s1>=s2)
False
False
True
True
ii) We can apply relational operators even for boolean types also.
In [57]:
In [60]:
a = 10
b = 20
if a>b:
print('a is greater than b')
else:
print('a is not greater than b')
a is not greater than b
print(10<20) # ==>True
print(10<20<30) # ==>True
print(10<20<30<40) # ==>True
print(10<20<30<40>50) # ==>False
True
True
True
False
3. Equality Operators:
Equality operators are used to check whether the given two values are equal or not. The following are the
equality operators used in Python.
1. Equal to (==)
2. Not Equal to (!=)
In [62]:
print(10==20)
print(10!=20)
False
True
In [63]:
print(1==True)
print(10==10.0)
print('karthi'=='karthi')
True
True
True
4. Logical operators:
1. and
2. or
3. not
You can apply these operators for boolean types and non-boolean types, but the behavior is different.
and ==> If both arguments are True then only result is True
In [67]:
In [68]:
print(True or True)
print(True or False)
print(False or True)
print(False or False)
True
True
True
False
In [69]:
print(not True)
print(not False)
False
True
5. Bitwise Operators:
In [6]:
In [7]:
print(True | False)
True
3. Bitwise ex-or (^):
In [9]:
print(2^4)
6
Behavior of Bitwise Operators:
& ==> If both bits are 1 then only result is 1 otherwise result is 0
| ==> If atleast one bit is 1 then result is 1 otherwise result is 0
^ ==>If bits are different then only result is 1 otherwise result is 0
~ ==> bitwise complement operator, i.e 1 means 0 and 0 means 1
<< ==> Bitwise Left shift Operataor
Bitwise Right Shift Operator ==> >>
In [8]:
print(4 & 5) # 100 & 101
print(4 | 5) # 100 | 101
print(4 ^ 5) # 100 ^ 101
4
5
1
In [10]:
print(~4) # 4 ==> 100
-5
Here, we have to apply complement for total bits, not for three bits (in case of 4). In Python minimum 28 bits
required to represent an integer.
6. Shift Operators:
After shifting the bits from left side, empty cells to be filled with zero.
In [13]:
print(10<<2)
40
After shifting the empty cells we have to fill with sign bit.( 0 for +ve and 1 for -ve).
In [14]:
print(10>>2)
2
In [15]:
7. Assignment Operators:
In [ ]:
x = 2
We can combine asignment operator with some other operator to form compound assignment operator.
Eg :
In [16]:
x = 10
x += 20 # x = x + 20
print(x)
30
1. If the operator operates on only one operand, we will call such operator as unary operator. For eg:, ~a.
2. If the operator operates on Two operands, we will call such operator as binary operator. For eg:, a + b.
3. If the operator operates on Three operands, we will call such operator as Ternary operator.
Syntax:
If condition is True then firstValue will be considered else secondValue will be considered.
In [1]:
a,b=23,43 # a =23 b = 43
c = 50 if a>b else 100
print(c)
100
Read two integer numbers from the keyboard and print minimum value using ternary operator.
In [2]:
In [5]:
In [6]:
8. Special Operators:
1. Identity Operators
2. Membership Operators
1. Identity Operators:
We can use identity operators for address comparison. There are two identity operators used in Python:
i) is
ii) is not
a=10
b=10
print(a is b)
x=True
y=True
print( x is y)
True
True
In [2]:
a="karthi"
b="karthi"
print(id(a))
print(id(b))
print(a is b)
1509178647664
1509178647664
True
In [3]:
list1=["one","two","three"]
list2=["one","two","three"]
print(id(list1))
print(id(list2))
print(list1 is list2)
print(list1 is not list2) # reference comaprison (is & is not)
print(list1 == list2) # content comparison (==)
1509178190144
1509178196736
False
True
True
2. Membership Operators
We can use Membership operators to check whether the given object present in the given collection.(It may
be String,List,Set,Tuple or Dict)
i) in
ii) not in
list1=["sunny","bunny","chinny","pinny"]
print("sunny" in list1)
print("tunny" in list1)
print("tunny" not in list1)
True
False
True
EX.NO 2: PROGRAM USING CONDITIONAL STATEMENTS
i) if statement:
In [23]:
if 10<20:
print('10 is less than 20')
print('End of Program')
10 is less than 20
End of Program
In [25]:
name=input("Enter Name:")
if name=="Karthi":
print("Hello Karthi Good Morning")
print("How are you!!!")
Enter Name:Karthi
Hello Karthi Good Morning
How are you!!!
In [26]:
name=input("Enter Name:")
if name=="Karthi":
print("Hello Karthi Good Morning")
print("How are you!!!")
Enter Name:Sourav
How are you!!!
In [27]:
name = input('Enter Name : ')
if name == 'Karthi':
print('Hello Karthi! Good Morning')
else:
print('Hello Guest! Good Morning')
print('How are you?')
In [31]:
i) while loop:
In [13]:
x=1
while x <=10:
print(x,end=' ')
x=x+1
1 2 3 4 5 6 7 8 9 10
In [14]:
n=int(input("Enter number:"))
sum=0
i=1
while i<=n:
sum=sum+i
i=i+1
print("The sum of first",n,"numbers is :",sum)
Enter number:10
The sum of first 10 numbers is : 55
Eg 3: write a program to prompt user to enter some name until entering RGM.
In [15]:
name=""
while name!="RGM":
name=input("Enter Name:")
print("Thanks for confirmation")
Enter Name:SREC
Enter Name:GPR
Enter Name:KSRM
Enter Name:AITS
Enter Name:RGM
Thanks for confirmation
In [1]:
s="Sahasra"
for x in s :
print(x)
S
a
h
a
s
r
a
In [3]:
s="Sahasra"
for x in s :
print(x,end='\t')
S a h a s r a
s = 'Hello'
for i in range(10):
print(s)
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
for i in range(0,11):
print(i,end=' ')
0 1 2 3 4 5 6 7 8 9 10
In [9]:
for i in range(21):
if(i%2!=0):
print(i,end=' ')
1 3 5 7 9 11 13 15 17 19
Enter List:10,20,30,40
The Sum= 100
In [12]:
list=eval(input("Enter List:"))
sum=0;
for x in list:
sum=sum+ x;
print("The Sum=",sum)
Enter List:[10,20,30,40]
The Sum= 100
Nested Loops:
Sometimes we can take a loop inside another loop,which are also known as nested loops.
Eg 1:
In [16]:
for i in range(3):
for j in range(2):
print('Hello')
Hello
Hello
Hello
Hello
Hello
Hello
Eg 2:
In [17]:
for i in range(4):
for j in range(4):
print('i = {} j = {}'.format(i,j))
i = 0 j = 0
i = 0 j = 1
i = 0 j = 2
i = 0 j = 3
i = 1 j = 0
i = 1 j = 1
i = 1 j = 2
i = 1 j = 3
i = 2 j = 0
i = 2 j = 1
i = 2 j = 2
i = 2 j = 3
i = 3 j = 0
i = 3 j = 1
i = 3 j = 2
i = 3 j = 3
In [23]:
Pattern-3:
12345
12345
12345
12345
12345
In [24]:
[28]:
n=int(input("Enter the number of rows: "))
for i in range(1,n+1):
for j in range(1,n+1):
print(n+1-j,end=" ")
print()
In [31]:
Demonstrate the following control transfer statements in Python with suitable examples.
In [3]:
for i in range(10):
if i==7:
print("processing is enough..plz break")
break
print(i)
0
1
2
3
4
5
6
processing is enough..plz break
cart=[10,20,600,60,70]
for item in cart:
if item>500:
print("To place this order insurence must be required")
break
print(item)
10
20
To place this order insurence must be required
i) continue:
We can use continue statement to skip current iteration and continue next iteration.
In [5]:
for i in range(10):
if i%2==0:
continue
print(i)
1
3
5
7
9
Eg 2:
In [6]:
cart=[10,20,500,700,50,60]
for item in cart:
if item >= 500:
print("We cannot process this item :",item)
continue
print(item)
10
20
We cannot process this item : 500
We cannot process this item : 700
50
60
Eg 3:
In [7]:
numbers=[10,20,0,5,0,30]
for n in numbers:
if n==0:
print("Hey how we can divide with zero..just skipping")
continue
print("100/{} = {}".format(n,100/n))
100/10 = 10.0
100/20 = 5.0
Hey how we can divide with zero..just skipping
100/5 = 20.0
Hey how we can divide with zero..just skipping
100/30 = 3.3333333333333335
In [9]:
cart=[10,20,30,40,50]
for item in cart:
if item>=500:
print("We cannot process this order")
break
print(item)
else:
print("Congrats ...all items processed successfully")
10
20
30
40
50
Congrats ...all items processed successfully
In [11]:
cart=[10,20,600,30,40,50]
for item in cart:
if item>=500:
print("We cannot process this order")
break
print(item)
else:
print("Congrats ...all items processed successfully")
10
20
We cannot process this order
ii) pass:
Example:
In [16]:
for i in range(100):
if i%9==0:
print(i)
else:
pass
0
9
18
27
36
45
54
63
72
81
90
99
In [33]:
In [34]:
In [35]:
In [36]:
Q5. Write a program to check whether the given number is even or odd?
In [37]:
Q6. Write a program to check whether the given number is in between 1 and 100?
In [40]:
n=int(input("Enter Number:"))
if n>=1 and n<=100 :
print("The number",n,"is in between 1 to 100")
else:
print("The number",n,"is not in between 1 to 100")
Enter Number:45
The number 45 is in between 1 to 100
In [41]:
n=int(input("Enter Number:"))
if n>=1 and n<=100 :
print("The number",n,"is in between 1 to 100")
else:
print("The number",n,"is not in between 1 to 100")
Enter Number:123
The number 123 is not in between 1 to 100
Q7. Write a program to take a single digit number from the key board and print it's value in English
word?
In [43]:
Q8. Python program to find all prime numbers within a given range.
In [24]:
Enter Range: 20
2
3
5
7
11
13
17
19
Enter Range: 20
2 3 5 7 11 13 17 19
In [27]:
count += 1
In [30]:
import math;
x1=int(input("Enter x1--->"))
y1=int(input("Enter y1--->"))
x2=int(input("Enter x2--->"))
y2=int(input("Enter y2--->"))
d1 = (x2 - x1) * (x2 - x1);
d2 = (y2 - y1) * (y2 - y1);
res = math.sqrt(d1+d2)
print ("Distance between two points:",res);
Enter x1--->5
Enter y1--->10
Enter x2--->15
Enter y2--->20
Distance between two points: 14.142135623730951
def gcd(a,b):
if(b==0):
return a
else:
return gcd(b,a%b)
a=int(input("Enter first number:"))
b=int(input("Enter second number:"))
print (gcd(a,b))
In [34]:
Enter a number:3
Enter a number:4
Exponent 81
EX.NO 4: PROGRAM USING NUMPY, A POPULAR LIBRARY FOR NUMERICAL
COMPUTING IN PYTHON
SOURCE CODE: -
importnumpyasnp #
Create arrays
a=np.array([1,2,3,4,5])
b =np.array([6,7,8,9,10])
# Basic operations
print("Array a:",a)
print("Array b:",b)
print("Sum of arrays a and b:", np.add(a, b))
#Aggregation operations
print("Minimum value of array a:", np.min(a))
#Reshaping arrays
c=np.array([[1,2],[3,4],[5,6]])
print("Arrayc:")
print(c)
print("Reshaped arrayc(2rows,3columns):")
print(np.reshape(c, (2, 3)))
#Transposingarrays
d=np.array([[1,2,3],[4, 5,6]])
print("Arrayd:") print(d)
print("Transposedarrayd"))
print(np.transpose(d))
OUTPUT:
Array a: [1 2 3 4 5]
Array b: [6789 10]
Sum of arrays a and b:[ 79111315]
Difference of arrays a and b:[-5-5-5-5-5]
Product of arrays a and b: [ 6 1424 36 50]
Division of arrays a and b:[0.166666670.285714290.375 0.44444444 0.5 ]
Square root of array a: [1.1.414213561.73205081 2.23606798]
Exponential of array a: [2.718281837.389056120.08553692 54.59815003 148.4131591 ]
Minimum value of array a: 1
Maximumvalueofarrayb:10
Import pandas as pd
#Selecting columns
name_age = df[['Name', 'Age']]
print("\n Name and Age columns:")
print(name_age)
#Filter in grows
filtered_df = df[df['Country'] == 'USA']
# Sorting by a column
sorted_df=df.sort_values('Salary', ascending=False)
#Aggregating data
average_salary = df['Salary'].mean()
print("\nAverage Salary:",average_salary)
# Adding a new column
df['Experience']=[3,6,4,8,5]
print("\nData Frame with added Experience column:")
print(df)
#Updating values
df.loc[df['Name'] == 'Emma', 'Salary'] = 65000
print("\nData Frame after updating Emma's Salary:")
print(df)
#Deleting a column
df=df.drop('Experience',axis=1)
print("\nData Frame after deleting Experience column:")
print(df)
OUTPUT:
FilteredDataFrame(Country='USA'):
NameAge CountrySalary
0John25 USA50000
SortedDataFrame(bySalaryindescendingorder):
NameAge CountrySalary
3Lisa32 UK70000
1Emma30 Canada60000
2Sam28Australia55000
4Tom27 Germany52000
0John25 USA50000
AverageSalary:57400.0
DataFrameafterdeletingExperiencecolumn:
NameAge CountrySalary
0 John25 USA50000
1 Emma30 Canada65000
2 Sam28Australia55000
3 Lisa32 UK70000
4 Tom27 Germany52000
EX.NO5b Create a data frame using a list of elements.
import numpy as np
import pandas as pd
data = np.array([['','Col1','Col2'],
['Row1',1,2],
['Row2',3,4]])
print(pd.DataFrame(data=data[1:,1:],
index = data[1:,0],
columns=data[0,1:]))