PYTHON PRACTICAL ASSIGNMENT SESSION 2021-22
1. x = input(“Enter any value: ”) #input() function to read console input
print(x)
2. x = ‘rahul’ #operations on string
print( x[0] ) #string indexing
print( x[-1] )
print( x[0 : 5] ) #string slicing
print( x[0 : -1] )
print( x[-1 : -2] )
y = ‘verma’
print( x+y ) #string concatenation
print( x[0] + y[0] )
print( x[2 : 4] + y[-1 : 0] )
print( x * 3) # string repetition
print( x[0] * 5 )
Output:- r
rahul
rahu
rahulverma
rv
hu
rahulrahulrahul
rrrrr
x = [ 5, ‘rahul’, 3.14, 759, 0.13 ] #operation on list
print( x[-2], x[0], x[1], x[4] ) #list indexing
print( x[ - 1 : -5 ], x[ 0 : 4 ], x[ -1 : 0 ] ) #list slicing
PYTHON PRACTICAL ASSIGNMENT SESSION 2021-22
y = [ ‘hello’, ‘world’ ]
print( x+y ) #list concatenation
print( y[0]+’ ’+x[1])
print( ‘smile’ + ’ ’ +y[1][0] + ’it’+ y[0][0] +’ ’+ x[1][4] + y[0][4]+’ve’ )
print( y[0][4]*3 + y[0][0]*5 + ‘ ’ + ’N’ + y[0][4]*7) #list repetition
Output :- 759 5 rahul 0.13
[0.13, 759, 3.14, ‘rahul’ 5] [5, ‘rahul’, 3.14, 759, 0.13]
[5, ‘rahul’, 3.14, 759, 0.13, ‘hello’, ‘world’]
hello rahul
smile with love
ooohhhhh Nooooooo
x = ( 5, ‘rahul’, 3.14, 759, 0.13 ) #operations on list
print( x[-2], x[0], x[1], x[4] ) #tuple indexing
print( x[ - 1 : -5 ], x[ 0 : 4 ], x[ -1 : 0 ] ) #tuple slicing
y = ( ‘hello’, ‘world’ )
print( x+y ) #tuple concatenation
print( y[0]+’ ’+x[1])
print( ‘smile’ + ’ ’ +y[1][0] + ’it’+ y[0][0] +’ ’+ x[1][4] + y[0][4]+’ve’ )
print( y[0][4]*3 + y[0][0]*5 + ‘ ’ + ’N’ + y[0][4]*7) #tuple repetition
Output :- 759 5 rahul 0.13
(0.13, 759, 3.14, ‘rahul’ 5) (5, ‘rahul’, 3.14, 759, 0.13)
(5, ‘rahul’, 3.14, 759, 0.13, ‘hello’, ‘world’)
hello rahul
smile with love
ooohhhhh Nooooooo
import itertools. #operations on dictionary
x = {
‘Brand’ : ‘Hero’,
‘Model’ : ‘splender’,
PYTHON PRACTICAL ASSIGNMENT SESSION 2021-22
‘Number’ : ‘RJ14 0000’,
‘Owners’ : [‘rahul’, ‘mukesh’, ‘ramesh’, ‘suresh’] }
print( x[ ‘Brand’ ], x[ ‘Owners’ ][ 0 ] ) #dict indexing
res = dict( itertools.islice(x.item(), 2) ) #dict slicing
y = x[ ‘Model’ ] + x[ ‘Owners’ ][ 3 ] )
print( y )
print( x[ ‘Color’ ] * 3 ) #dict repetition
Output :- Hero rahul
Brand : Hero
{‘Brand’ : ‘Hero’, ‘Model’ : ‘splender’}
splendersuresh
x = { ‘hello’, 99, .39, 8, ‘ankit’, 2}#set objects are not subscriptable
print( x )
Output :- { ‘hello’, 99, .39, 8, ‘ankit’, 2}
PYTHON PRACTICAL ASSIGNMENT SESSION 2021-22
5. import random
random.randint( 0, 99) #return random a integer x<= I >=y
Output :- 57
random.randrang( 57, 999, 3) #returns random an integer
#in between range randarang( start, stop, step )
Output :- 927
random.random() #returns a random floating value
Output :- 0.5313843048739985
import math
import random
print( math.sin( random.random() ) ) #sin(),cos() function defined
#in math module
print( math.cos(random.randint(49,99) ) )
Output :- 0.7739405962953605
0.7301735609948197
6. def func1( x, y ):
print(‘In func1\n')
a = x + y
return a
def func2( x, y ):
print(‘in func2\n’)
a = x * y
return a
def func3( x, y ):
print(‘in func3\n’)
return a
a = x - y
PYTHON PRACTICAL ASSIGNMENT SESSION 2021-22
a = func1( 53, 89.2)
b = func2( ‘python’, 4)
c = func3( math.log(5), random.random())
print(a, b, c)
Output :- in func1
in func2
in func3
142.2 pythonpythonpythonpython 0.9013081295104165
7. fp = open( ‘/Users/rahulverma/desktop/temp.txt’, ‘r’) #load file in
# fp open() function is use for open a file of given location and mode
print( fp.read() ) #will read the whole content of file
print( fp.read( 5 ) ) #will read first five chracter of file
line = fp.readline()
for I in line: #will read the whole file line by line
print( i )
fp.close() #close the current open file
fp = open( ‘/Users/rahulverma/desktop/temp.txt’, ‘w’)
y = input(‘input to file: ’)
fp.write( y ) #this will input write on file but remove all existing
content of the file
fp.close() #will close the current opend file
fp = open(‘/Users/rahulverma/desktop/temp.txt’,’a’) #appending
x = input(‘input to file: ’)
fp.write( x ) #use to give input to file
fp.close(). #input will print on the file after the file close
#coping file content
fp = open( ‘/Users/rahulverma/desktop/temp.txt’, ‘r’ )
fc = open( ‘/Users/rahulverma/desktop/coied_file.txt’, ‘a’)
for line in fp:
PYTHON PRACTICAL ASSIGNMENT SESSION 2021-22
fc.write( line )
fp.close()
fc.close()
PYTHON PRACTICAL ASSIGNMENT SESSION 2021-22
10. Import numpy as np
x = np.array( [ [ 1, 2, 3, 4, 5 ] ,[ 6, 7, 8, 9, 10 ] ] )
print( x[0][1], x[1][4] ) #numpy array indexing
Output :- 2 10
print( x[ 0 ][ 0:4 ], x[ 0, 0:4] , x[1, 0:-1] ) #numpy array slicing
Output :- [ 1, 2, 3, 4, 5 ] [ 1, 2, 3, 4, 5]
print( ‘shape before reshaping ‘, x.shape )
b = x.reshape( 5,2 ) #array reshaping (only way of reshaping x)
print( ‘array after reshaping ’, b.shape, b )
Output :- shape before reshaping ( 2, 5 )
[[ 1 2 ]
[ 3 4 ]
[ 5 6 ]
[ 7 8 ]
[ 9 10 ]]
#numpy array joining
y = np.array( [ [ 11, 12, 13, 14, 15], [16, 17, 18, 19, 20] ] )
print( np.concatenate( ( x, y ) ) ) #default according to row
print( np.concatenate( ( x, y ), axis =1 ) ) #according to column
print( np.stack( ( x, y ) ) ) # x/y
print( np.vstack( (x, y) ) ) # x / y
print( np.hstack( ( x, y ) ) ) # x y
Output :- [ [ 1 2 3 4 5 ]
[ 6 7 8 9 10 ]
[ 11 12 13 14 15 ]
[ 16 17 18 19 20 ] ]
[ [ 1 2 3 4 5 11 12 13 14 15 ]
[ 6 7 8 9 10 16 17 18 19 20 ] ]
PYTHON PRACTICAL ASSIGNMENT SESSION 2021-22
[ [ 1 2 3 4 5 ]
[ 6 7 8 9 10 ] ]
[ [ 11 12 13 14 15 ]
[ 16 17 18 19 20 ] ] #stack
[ [ 1 2 3 4 5 ]
[ 6 7 8 9 10 ]
[ 11 12 13 14 15 ]
[ 16 17 18 19 20 ] ] #vstack
[ [ 1 2 3 4 5 11 12 13 14 15 ]
[ 6 7 8 9 10 16 17 18 19 20 ] ] #hsatck
#numpy array splitting
z = np.array( [1, 2, 3, 4, 5, 6 ] )
print( np.array_split( z, 3 ) )
print( np.array_split( z, 4 ) )
a = np.array_split( x, 2 )
print( a[ 0 ] )
print( a[ 1 ] )
print( np.array_split( x, 4 ) )
Output :- [ array( [1, 2] ), array( [3, 4] ), array( [5, 6] ) ]
[ array( [1, 2] ), array( [3, 4] ), array( [5] ), array( [6] ) ]
[[12345]]
[ [ 6 7 8 9 10 ] ]
[ array( [ [1, 2, 3, 4, 5 ] ] ), array( [ [6, 7, 8, 9, 10] ] ), array( [ ],
shape=(0,5), dtype=int64 ), array( [ ] ), shape=(0,5), dtype=int64 ]
PYTHON PRACTICAL ASSIGNMENT SESSION 2021-22
11. import numpy as np
x = np.array( [ 10, 20, 30, 40, 50, 60 ] )
y = x * ( 3.14 / 180 )
#universal mathematical functions
print( np.sin( y[ 5 ] ) ) #sin( ) function
print( np.cos(y[ 5 ] ) ) #cos( ) function
print( np.tan( y[ 5 ] ) ) #tan( ) function
print( np.arccos( y[ 1 ] ) ) #inverse cos( ) function
print( np.arcsin( y[ 4 ] ) ) #inverse sin( ) function
print( np.arctan( y[ 5 ] ) ) #inverse tan( ) function
print( np.sinh( y[ 5 ] ) ) #hyperbolic sinh( ) function
print( np.cosh( y[ 5 ] ) ) #hyperbolic cosh( ) function
print( np.tanh( y[ 5 ] ) ) #hyperbolic tanh( ) function
print( np.rad2deg( y[ 5 ] ) ) #convert radian to degree
print( np.rad2deg( x[ 5 ] ) ) #convert degree to radian
Output :- 0.8657598394923445
0.500459689008205
1.7299292200897907
1.2144110951818066
1.0597274793641782
nan
0.8081955160998497
1.248517659007662
1.5996238135430383
0.7805070469926899
59.96958255702618
3437.746770784939
#universal statistical function
print( np.mean( x ) ) #compute mean of array
print( np.median( x ) ) #compute median of array
print( np.std( x ) ) #compute standard deviation
PYTHON PRACTICAL ASSIGNMENT SESSION 2021-22
print( np.var( x ) ) #compute variance of array
print( np.average( x ) ) #compute average of array
print( np.amin( x ) ) #returns minimum value present
print( np.amax( x ) ) #returns maximum value present
print( np.percentile( x, 70 ) ) #calculate percentile
Output :- 35.0
35.0
17.07825127659933
291.6666666666667
35.0
10
60
45.0
PYTHON PRACTICAL ASSIGNMENT SESSION 2021-22
12. Import pandas as pd
data = pd.read_csv( ‘/Users/rahulverma/downloads/Births-and-
deaths/births-deaths-by-region.csv’)
#statistical functions in pandas
print( data.mean( ) ) #returns mean of every column except
object)
print( data.median( ) ) #returns median of every column except
object
print( data[‘Count’].mode( ) ) #returns mode of every column
print( data.max( ) ) #returns maximum value of every column
except object
PYTHON PRACTICAL ASSIGNMENT SESSION 2021-22
print( data.min( ) ) #returns minimum value of every
column
print( data.std( ) ) #returns standard deviation of every column
print( data.var( ) ) #returns variance of every column
print( data.count( ) ) #returns number of non-null observations
#comparison operations in pandas
PYTHON PRACTICAL ASSIGNMENT SESSION 2021-22
PYTHON PRACTICAL ASSIGNMENT SESSION 2021-22
15. 1. Handeling missing values in data frames
a. data.fillna(0) fill 0 in missing values
b. data.isnull() returns false for non missing values
2. apply() - method is use for giving dataframe to function to perform
various arithmetic operations
PYTHON PRACTICAL ASSIGNMENT SESSION 2021-22
map() - method is use for mapping series in dataframe
3. String operations in dataframes
PYTHON PRACTICAL ASSIGNMENT SESSION 2021-22
4. Bar plot
PYTHON PRACTICAL ASSIGNMENT SESSION 2021-22
PYTHON PRACTICAL ASSIGNMENT SESSION 2021-22
3. problem - find, he/she is voter or not
age = int( input( ‘Enter age: ’ ))
if age>18 and age<120:
print( ‘You are a voter’ )
else:
prin( ‘Invalid age criteria’ )
problem - find sum of the digits of given number
x = int( input( ‘Enter any number: ’ ) )
while( x> 0):
a = x %10
sum = sum + a
x = x//10
PYTHON PRACTICAL ASSIGNMENT SESSION 2021-22
8. Exception handling - try, except, finally and raise keywords are use
to handle exception
try - this keyword’s code block identify the upcoming exceptions
except - this keyword is use to catch the specific exception
finally - this keywords blocks execute always after the try and except’s
block
raise - the raise keyword allows programmer to force a specific
exception to occur example: NameError(), ZeroDivisionError()
try:
k = 5 / 0 #after the exception the control will goes to except
print( k )
except ZeroDivisionError:
print( ‘exception caught - divide by zero error')
finally:
print( ‘this is always execute’ )
Note:- Exception is the base class for all exceptions.
9. class py:
def pow(self, x, n):
if x==0 or x==1 or n==1:
return x
if x==-1:
if n%2 ==0:
return 1
else:
return -1
if n==0:
return 1
if n<0:
return 1/self.pow(x,-n)
val = self.pow(x,n//2)
PYTHON PRACTICAL ASSIGNMENT SESSION 2021-22
if n%2 ==0:
return val*val
return val*val*x
print(py().pow(2, -3));
print(py().pow(3, 5));
print(py().pow(100, 0));
PYTHON PRACTICAL ASSIGNMENT SESSION 2021-22
4. # function to check if two strings are
# anagram or not
s1 ="listen"
s2 ="silent"
if(sorted(s1)== sorted(s2)):
print("The strings are anagrams.")
else:
print("The strings aren't anagrams.")
test_list3 = [1, 4, 5, 6, 5]
test_list4 = [3, 5, 7, 2, 5]
test_list3 = test_list3 + test_list4
print ("Concatenated list using + : "
+ str(test_list3))
# initialising _list
ini_tuple = [('b', 100), ('c', 200), ('c', 45),
('d', 876), ('e', 75)]
print("intial_list", str(ini_tuple))
# removing tuples for condition met
result = []
for i in ini_tuple:
if i[1] <= 100:
result.append(i)
print ("Resultant tuple list: ", str(result))
PYTHON PRACTICAL ASSIGNMENT SESSION 2021-22
#a Set
set1 = set()
set1 = set("GeeksForGeeks")
print("\nSet with the use of String: “)
print(set1)
# the use of Constructor
String = ‘hello world'
set1 = set(String)
print(set1)
set1 = set(["Geeks", "For", "Geeks"])
print("\nSet with the use of List: “)
print(set1)
#dictionary
test_dict1 = {'gfg' : 1, 'best' : 2, 'for' : 4, 'geeks' : 6}
test_dict2 = {'for' : 3, 'geeks' : 5}
print("The original dictionary 1 is : " + str(test_dict1))
print("The original dictionary 2 is : " + str(test_dict2))
# Update dictionary with other dictionary
for key in test_dict1:
if key in test_dict2:
test_dict1[key] = test_dict2[key]
print("The updated dictionary is : " + str(test_dict1))
PYTHON PRACTICAL ASSIGNMENT SESSION 2021-22
PYTHON PRACTICAL ASSIGNMENT SESSION 2021-22
PYTHON PRACTICAL ASSIGNMENT SESSION 2021-22
PYTHON PRACTICAL ASSIGNMENT SESSION 2021-22
PYTHON PRACTICAL ASSIGNMENT SESSION 2021-22
PYTHON PRACTICAL ASSIGNMENT SESSION 2021-22
PYTHON PRACTICAL ASSIGNMENT SESSION 2021-22
PYTHON PRACTICAL ASSIGNMENT SESSION 2021-22
PYTHON PRACTICAL ASSIGNMENT SESSION 2021-22
PYTHON PRACTICAL ASSIGNMENT SESSION 2021-22
PYTHON PRACTICAL ASSIGNMENT SESSION 2021-22
PYTHON PRACTICAL ASSIGNMENT SESSION 2021-22
PYTHON PRACTICAL ASSIGNMENT SESSION 2021-22