Key Answers Internal - 2
Key Answers Internal - 2
Namespace in Python
In python we deal with variables, functions, libraries and modules etc. There is a chance the
name of the variable you are going to use is already existing as name of another variable or as
the
name of another function or another method. In such scenario, we need to learn about how all
these
names are managed by a python program. This is the concept of namespace.
Following are the three categories of namespace
1) Local Namespace: All the names of the functions and variables declared by a program are held
in
this namespace. This namespace exists as long as the program runs.
2) Global Namespace: This namespace holds all the names of functions and other variables that
are
included in the modules being used in the python program. It encompasses all the names that
are
part of the Local namespace.
3) Built-in Namespace: This is the highest level of namespace which is available with default
names
available as part of the python interpreter that is loaded as the programing environment. It
encompasses Global Namespace which in turn encompasses the local namespace.
Example:
a = 10 # global variable
def function_local( ):
b=20
a=30 # local variable
print(a)
print(b)
def function_inner( ):
b=35
a=25
print(a)
print(b)
function_inner( )
function_local( ) #function call
print(a)
Packages
Packages are a way of structuring many packages and modules which help in a well-
organized hierarchy of data set, making the directories and modules easy to access.
To tell Python that a particular directory is a package, we create a file named __init__.py inside it
and
then it is considered as a package and we may create other modules and sub-packages within it.
This __init__.py file can be left blank or can be coded with the initialization code for the package.
Install numpy
pip install numpy
Example:
import numpy
arr = numpy.array([1, 2, 3, 4, 5])
print(arr)
NumPy as np
NumPy is usually imported under the np alias.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
print(np.__version__)
4.What are the numpy packages for manipulation function with example?
transpose( ):This function permutes the dimension of the given array. It returns a view wherever
possible.
import numpy as np
a = np.arange(12).reshape(3,4)
print('The original array is:')
print(a)
print('The transposed array is:')
print(np.transpose(a))
concatenate( ):
Concatenation refers to joining. This function is used to join two or more arrays of the same
shape
along a specified axis.
import numpy as np
a = np.array([[1,2],[3,4]])
print('First array:')
print(a)
b = np.array([[5,6],[7,8]])
print('Second array:')
print(b)
append( ):This function adds values at the end of an input array. The append operation is not
inplace,
a new array is allocated. Also the dimensions of the input arrays must match otherwise
ValueError
will be generated.
import numpy as np
a = np.array([[1,2,3],[4,5,6]])
print('First array:')
print(a)
print('Append elements to array:')
print(np.append(a, [7,8,9]))
split( ):This function divides the array into subarrays along a specified axis.
import numpy as np
a = np.arange(9)
print('First array:')
print(a)
print('Split the array in 3 equal-sized subarrays:')
b = np.split(a,3)
print(b)
class MyError(Exception):
# Constructor or Initializer
def __init__(self, value):
self.value = value
# __str__ is to print() the value
def __str__(self):
return(repr(self.value))
try:
raise(MyError(3*2))
# Value of Exception is stored in error
except MyError as error:
print('A New Exception occured: ',error.value)
Output:
Enter a number: 7
Not an even number!
Enter a number: 6
0.16666…
6.a)Construct a code for average number of points scored by each team in the DataFrame?
import pandas as pd
points_table = {'Team_':['MI', 'CSK', 'Devils', 'MI', 'CSK',
'RCB', 'CSK', 'CSK', 'KKR', 'KKR', 'KKR', 'RCB'],
'Rank_' :[1, 2, 2, 3, 3,4 ,1 ,1,2 , 4,1,2],
'Year_' :[2014,2015,2014,2015,2014,2015,2016,2017,2016,2014,2015,2017],
'Point_':[876,789,863,673,741,812,756,788,694,701,804,690]}
df = pd.DataFrame(points_table)
print(df)
def read_file(filename):
try:
with open(filename, 'r') as file:
for line in file:
print(line.strip()) # Print each line without leading/trailing whitespace
except FileNotFoundError:
print(f"Error: The file '{filename}' does not exist.")
# Example usage
filename = 'example.txt' # Change this to your file name
read_file(filename)