0% found this document useful (0 votes)
18 views6 pages

Key Answers Internal - 2

Uploaded by

Mubeena Nasir
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views6 pages

Key Answers Internal - 2

Uploaded by

Mubeena Nasir
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Key Answers Internal -2

Subject - Python Sem-3

1.Explain Namespace in Python with suitable example?

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)

2.Explain Packages with suitable example?

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.

To create a package in Python, we need to follow these three simple steps:


1. First, we create a directory and give it a package name, preferably related to its operation.
2. Then we put the classes and the required functions in it.
3. Finally we create an __init__.py file inside the directory, to let Python know that the directory
is a
package.

< --------- __init__.py ----------->


Blank
< --------- add.py ----------->
def addition(a,b):
print(a+b)
Program using package:
from calculator import add
add.addition(10,20)

3.Why Numpy is faster than List with example?

Why is NumPy Faster Than Lists?


➢ NumPy arrays are stored at one continuous place in memory unlike lists, so processes can
access
and manipulate them very efficiently.
➢ This behavior is called locality of reference in computer science.
➢ This is the main reason why NumPy is faster than lists. Also it is optimized to work with latest
CPU
architectures.

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?

NumPy package for manipulation functions


reshape( ):This function gives a new shape to an array without changing the data.
import numpy as np
a = np.arange(8)
print('The original array:')
print(a)
b = a.reshape(4,2)
print('The modified array:')
print(b)

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)

5.a)Develop a program for user defined exceptions?

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)

5.b)Develop a code to print the reciprocal of even number?

# program to print the reciprocal of even numbers


try:
num = int(input("Enter a number: "))
assert num % 2 == 0
except:
print("Not an even number!")
else:
reciprocal = 1/num
print(reciprocal)

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)

6.b)Construct a program to reading a file in python?

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)

You might also like