0% found this document useful (0 votes)
14 views29 pages

PWP Assignment 1

The document discusses various Python concepts like modes, features, data types, operators, and comments. It provides definitions and examples of different data types like integers, booleans, floats, strings, lists, tuples and dictionaries. It also explains identity operators, for loops, membership and assignment operators, and multiline comments.

Uploaded by

rohitdhande79
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)
14 views29 pages

PWP Assignment 1

The document discusses various Python concepts like modes, features, data types, operators, and comments. It provides definitions and examples of different data types like integers, booleans, floats, strings, lists, tuples and dictionaries. It also explains identity operators, for loops, membership and assignment operators, and multiline comments.

Uploaded by

rohitdhande79
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/ 29

UNIT 1

Q. Name different modes of Python


Ans: Python has two basic modes:
● Script (Normal Mode)
● Interactive Mode

Q. List Python features. (Any four)


Ans:
● Easy to Learn and Use
● Interactive Mode
● Expressive Language
● Interpreted Language
● Cross-platform Language
● Portable
● Free and Open Source
● Object-Oriented Language
● Extensible
● Large Standard Library
● GUI Programming Support
● Integrated
● Databases
● Scalable

Q. List data types used in Python. Explain any two with example.
Ans: Data types in Python programming includes:
● Numbers: Represents numeric data to perform mathematical operations.
● String: Represents text characters, special symbols or alphanumeric data.
● List: Represents sequential data that the programmer wishes to sort, merge etc.
● Tuple: Represents sequential data with a little difference from list.
● Dictionary: Represents a collection of data that associate a unique key with each value.
● Boolean: Represents truth values (true or false).

1. Integers (int Data Type): An integer is a whole number that can be positive (+) or negative (−).
Integers can be of any length, it is only limited by the memory available.

Example: For number data types are integers.


>>>a = 10
>>>b = -10
To determine the type of a variable type() function is used.
>>>type(a)
>>> <class 'int'>
2. Boolean (Bool Data Type): The simplest build-in type in Python is the bool type, it represents the
truth values False and True. Internally the true value is represented as 1 and false is 0.

Example:
>>>a = 18 > 5
>>>print(a)
True
>>>b = 2 > 3
>>>print(b)
False

Q. Explain building blocks of python.


Ans:
Character set: All characters that python can recognize. The below table illustrates the Python
character set along with examples.

Character Set Example

Letters: Upper case and lower case english A-Z, a-z


alphabets

Digits: all digits 0-9

Special symbols space,+,-,**,*,%,//,/,==,!=,>,<

Whitespaces Blank space,tabs

Other unicode characters All ASCII and Unicode characters

Tokens: Tokens in python are building blocks of the Python programming language. The role letters
and words play for the English language, Similar to role token play for a python programming
language.

Python has the following tokens:


1) keywords
2) identifiers
3) literals
a) String literals
b) Numeric literals
c) Boolean Literals
d) Special literal None

Tokens Example

Keywords: Words that are already defined False, True, if, elif, else, for, while, pass,
and convey a special meaning to the continue, lambda, return, finally, import, def
language compiler/interpreter
Identifiers: names given to different parts of def square, num = 20, a_lst=[1,2,3]
program like variables, functions,object, here square, num and a_lst are identifiers.
class, names given to different datatypes.

Literals/Constants: Data items that have String: ‘Mayank’,‘abc’,‘anish’;


fixed values. Numeric: 1,1.2,4,-3.95;
Boolean: True,False

Special literal None; meaning nothing

Q. Describe indentation in Python.


Ans: Indentation refers to the spaces at the beginning of a code line. Python indentation
refers to adding white space before a statement to a particular block of code. In another word,
all the statements with the same space to the right, belong to the same code block.

Q. Write different data types in python with suitable example.


Ans:
Data types in Python programming includes:
● Numbers: Represents numeric data to perform mathematical operations.
● String: Represents text characters, special symbols or alphanumeric data.
● List: Represents sequential data that the programmer wishes to sort, merge etc.
● Tuple: Represents sequential data with a little difference from list.
● Dictionary: Represents a collection of data that associate a unique key with each value.
● Boolean: Represents truth values (true or false).

1. Integers (int Data Type): An integer is a whole number that can be positive (+) or negative (−).
Integers can be of any length, it is only limited by the memory available.

Example: For number data types are integers.


>>>a = 10
>>>b = -10
To determine the type of a variable type() function is used.
>>>type(a)
>>> <class 'int'>

2. Boolean (Bool Data Type): The simplest build-in type in Python is the bool type, it represents the
truth values False and True. Internally the true value is represented as 1 and false is 0.
Example:
>>>a = 18 > 5
>>>print(a)
True
>>>b = 2 > 3
>>>print(b)
False

3. Floating-Point/Float Numbers (Float Data Type): Floating-point number or Float is a


positive or negative number with a fractional part. A floating point number is accurate up to
15 decimal places. Integer and floating points are separated by decimal points. 1 is integer,
1.0 is floating point number.

Example: Floating point number.


x=10.1
type(x)
<class 'float'>

4. Complex Numbers (Complex Data Type): Complex numbers are written in the form, x +
yj, where x is the real part and y is the imaginary part.

Example:
Complex number.
>>>x = 3+4j
>>>print(x.real)
3.0
>>>print(x.imag)
4.0

5. String Data Type: String is a collection of group of characters. Strings are identified as a
contiguous set of characters enclosed in single quotes (' ') or double quotes (" "). Any letter, a
number or a symbol could be a part of the string. Strings are unchangeable (immutable).
Once a string is created, it cannot be modified.

Example: For string data type.


>>> s1="Hello" #string in double quotes
>>> s2='Hi' #string in single quotes
>>> s3="Don't open the door" #single quote string in double quotes
>>> s4='I said "yipee"' #double quote string in single quotes
>>>type(s1)
<class 'str'>
6. List Data Type: List is an ordered sequence of items. It is one of the most used datatype in
Python and is very flexible. List can contain heterogeneous values such as integers, floats,
strings, tuples, lists and dictionaries but they are commonly used to store collections of
homogeneous objects. The list datatype in Python programming is just like an array that can
store a group of elements and we can refer to these elements using a single name. Declaring a
list is pretty straight forward. Items separated by commas ( , ) are enclosed within brackets [
].

Example: For list.


>>> first=[10, 20, 30] # homogenous values in list
>>> second=["One","Two","Three"] # homogenous values in list
>>> first
[10, 20, 30]
>>> second
['One', 'Two', 'Three']
>>> first + second # prints the concatenated lists
[10, 20, 30, 'One', 'Two', 'Three']

7. Tuple Data Type: Tuple is an ordered sequence of items same as list. The only difference
is that tuples are immutable. Tuples once created cannot be modified. It is defined within
parentheses ( ) where items are separated by commas ( , ). A tuple data type in python
programming is similar to a list data type, which also contains heterogeneous items/elements.

Example: For tuple.


>>> a=(10,'abc',1+3j)
>>> a
(10, 'abc', (1+3j))
>>> a[0]
10
>>> a[0]=20
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>

8. Dictionary: Dictionary is an unordered collection of key-value pairs. It is the same as the


hash table type. The order of elements in a dictionary is undefined, but we can iterate over the
following:
● The key
● The value
● The items (key-value pairs) in a dictionary.
When we have the large amount of data, the dictionary data type is used. Items in dictionaries
are enclosed in curly braces { } and separated by the comma (,). A colon (:) is used to
separate key from value. Values can be assigned and accessed using square braces ([]).

Example: For dictionary data type.


>>> dic1={1:"First","Second":2}
>>> dic1
{1: 'First', 'Second': 2}
>>> type(dic1)
<class 'dict'>
>>> dic1[3]="Third"
>>> dic1
{1: 'First', 'Second': 2, 3: 'Third'}
>>> dic1.keys()
dict_keys([1, 'Second', 3])
>>> dic1.values()
dict_values(['First', 2, 'Third'])

Q. Describe Multiline comment in python.


Ans:
● In some situations, multiline documentation is required for a program. If we have
comments that extend multiple lines, one way of doing it is to use hash (#) in the
beginning of each line. Another way of doing this is to use quotation marks, either '''
or """.
● Similarly, when it sees the triple quotation marks ''' it scans for the next ''' and ignores
any text in between the triple quotation marks.

● Example: For multiline comment.


'''This is first python program
Print is a statement'’

UNIT 2

Q. List identity operators in python


Ans: Identity operators in Python are
● is
● is not

Q. Write a program to print following


1
12
123
1234
Ans:
for i in range(1, 5):
for j in range(1, i + 1):
print(j, end=' ')
print()

Q. Explain membership and assignment operators with example


Ans:
Membership Operators: The membership operators in Python are used to find the existence
of a particular element in the sequence, and used only with sequences like string, tuple, list,
dictionary etc.
Membership operators are used to check an item or an element that is part of a string, a list or
a tuple. A membership operator reduces the effort of searching an element in the list. Python
provides ‘in’ and ‘not in’ operators which are called membership operators and used to test
whether a value or variable is in a sequence.

Sr. No Operator Description Example

1 in True if value is found in list or in >>> x="Hello World"


sequence, and false if item is not in >>> print('H' in x)
list or in sequence. True

2 not in True if value is not found in list or in >>> x="Hello World”


sequence, and false if the item is in >>> print("Hello" not in x)
list or in sequence. False

Assignment Operators (Augmented Assignment Operators): Assignment operators are


used in Python programming to assign values to variables. The assignment operator is used to
store the value on the right-hand side of the expression on the left-hand side variable in the
expression.

For example, a = 5 is a simple assignment operator that assigns the value 5 on the right to
the variable a on the left.
There are various compound operators in Python like a += 5 that adds to the variable and
later assigns the same. It is equivalent to a = a + 5.
Following table shows assignment operators in Python programming:

Sr. No Operator Description Example

1 = Assigns values from right side c = a + b


operands to left side operands.
assigns value of a + b into
c

2 += It adds right operand to the left c += a


operand and assign the result to left is equivalent to c = c + a
operand.
Q. Explain decision making statements If-else, if-elif-else with example.
Ans:
The if-else statement: if statements executes when the conditions following if are true and it
does nothing when the condition is false. The if-else statement takes care of a true as well as
false condition.

Syntax-1: Syntax-2:

if condition: if condition:
Statement(s) if_Block
else: else:
Statement(s) else_Block

Example:

i = 20
if i < 15:
print("less than 15")
else:
print("greater than 15")

Output:
greater than 15

Conceptual Diagram:
if-elif-else (ladder) statements: Here, a user can decide among multiple options. The if
statements are executed from the top down. As soon as one of the conditions controlling the
if is true, the statement associated with that if is executed, and the rest of the ladder is
bypassed. If none of the conditions is true, then the final else statement will be executed.

Syntax:
if (condition-1):
statement
elif (condition-2):
statements
.
.
elif(condition-n):
statements
else:
statements

Example:
i = 20
if i == 10:
print("i is 10")
elif i == 15:
print("i is 15")
elif i == 20:
print("i is 20")
else:
print("i is not present")

Output:
i is 20

Concept Diagram:

Q. List comparision operators in Python.


Ans:
Comparison operators in Python are:

Operator Meaning

== Equal to

!= Not Equal to
< Less than

> Greater than

Q. Describe bitwise operators in Python with example.


Ans: Bitwise operators acts on bits and performs bit by bit operation. Assume a=10 (1010)
and b=4 (0100)

Operato Meaning Description Example


r

& Binary AND This operation performs AND a &b =


operation between operands. Operator 1010 & 0100
copies a bit, to the result, if it exists in = 0000 = 0
both operands

| Bitwise OR This operation performs OR operation a | b = 1010 | 0100 =


between operands. It copies a bit, if it 1110 = 14
exists in either operand.

^ Bitwise XOR This operation performs XOR a ^ b=1010 ^ 0100 =


operations between operands. It 1110 =14
copies the bit, if it is set in one
operand but not both.

~ Bitwise One’s It is unary operator and has the effect ~a = ~ 1010


Complement of 'flipping' bits i.e. opposite the bits = 0101
of operand.

Q. Write python program to illustrate if else ladder.


Ans:
i = 20
if i == 10:
print("i is 10")
elif i == 15:
print("i is 15")
elif i == 20:
print("i is 20")
else:
print("i is not present")

Output:
i is 20

Q. Describe membership operators in python.


Ans:
● The membership operators in Python are used to find the existence of a particular
element in the sequence, and used only with sequences like string, tuple, list,
dictionary etc.
● Membership operators are used to check an item or an element that is part of a string,
a list or a tuple. A membership operator reduces the effort of searching an element in
the list.
● Python provides ‘in’ and ‘not in’ operators which are called membership operators
and used to test whether a value or variable is in a sequence.

Q. Describe Keyword "continue" with example.


Ans:
● The continue statement in Python returns the control to the beginning of the while
loop.
● The continue statement rejects all the remaining statements in the current iteration of
the loop and moves the control back to the top of the loop.
● Syntax: continue
● Example: For continue statement.

i=0
while i < 10:
i += 1
if i == 5:
continue
print("i =", i)

Output:
i=1
i=2
i=3
i=4
i=6
i=7
i=8
i=9
i=10

Q. Write a Python program to find the factorial of a number provided by the user.
Ans:
num = int(input("Enter Number: "))
fact = 1
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1, num + 1):
fact *= i
print("The factorial of", num, "is", fact)

Output:
Enter Number: 5
The factorial of 5 is 120

Q. Explain Bitwise operator in Python with appropriate example.


Ans:
1. Bitwise AND (&): Performs a bitwise AND operation on each pair of corresponding
bits. It returns 1 if both bits are 1, otherwise 0.

Example:
a = 5 # binary: 0101
b = 3 # binary: 0011
result = a & b # binary result: 0001 (decimal 1)

2. Bitwise OR (|): Performs a bitwise OR operation on each pair of corresponding bits.


It returns 1 if at least one of the bits is 1.

Example:
a = 5 # binary: 0101
b = 3 # binary: 0011
result = a | b # binary result: 0111 (decimal 7)

3. Bitwise XOR (^): Performs a bitwise XOR (exclusive OR) operation on each pair of
corresponding bits. It returns 1 if the bits are different, otherwise 0.

Example:
a = 5 # binary: 0101
b = 3 # binary: 0011
result = a ^ b # binary result: 0110 (decimal 6)

4. Bitwise NOT (~): Performs a bitwise NOT operation, which inverts all the bits. It
turns 0s into 1s and vice versa.

Example:
a = 5 # binary: 0101
result = ~a # binary result: 1010 (decimal -6 due to two's complement
representation)
5. Left Shift (<<): Shifts the bits of the left operand to the left by the number of
positions specified by the right operand.

Example:
a = 5 # binary: 0101
result = a << 2 # binary result: 10100 (decimal 20)

6. Right Shift (>>): Shifts the bits of the left operand to the right by the number of
positions specified by the right operand. Depending on the number's sign, it fills the
vacant positions with 0s (logical right shift) or the most significant bit (arithmetic
right shift).

Example:
a = 16 # binary: 10000
result = a >> 2 # binary result: 00100 (decimal 4)

UNIT 3

Q. Give two differences between list and tuple.


Ans:

List Tuple

i) Lists are mutable i) Tuples are immutable

ii) Lists consume more memory ii) Tuple consume less memory as compared
to the list

iii) Lists have several built-in methods iii) Tuple does not have many built-in
methods.

iv) The unexpected changes and errors are iv) In tuple, it is hard to take place.
more likely to occur.

v) The List has the variable length. v) The tuple has a fixed length.

vi) List operations are more error prone. vi) Tuples operations are safe.

vii) Lists can be used to store homogeneous vii) Tuples are used to store only
and heterogeneous elements. heterogeneous elements.

viii) List is useful for insertion and deletion viii) Tuple is useful for readonly operations
operations. like accessing elements.

ix) List iteration is slower and is time ix) Tuple iteration is faster.
consuming.

Q. Explain four Built-in tuple functions in python with example.


Ans:
1. count():
● The count() method returns the number of times a specified element appears in the
tuple.

● Example:
my_tuple = (1, 2, 2, 3, 4, 2)
count = my_tuple.count(2)
print(count) # Output: 3 (2 appears three times)

2. index():
● The index() method returns the index of the first occurrence of a specified element in
the tuple.

● Example:
my_tuple = (1, 2, 3, 4, 5)
index = my_tuple.index(3)
print(index) # Output: 2 (3 is at index 2)

3. len():
● The len() function returns the number of elements in the tuple.

● Example:
my_tuple = (1, 2, 3, 4, 5)
length = len(my_tuple)
print(length) # Output: 5 (there are 5 elements in the tuple)

4. max():
● The max() function returns the maximum value from a tuple of numbers or the
maximum element based on the default or a specified key function.

● Example:
num_tuple = (10, 20, 5, 30)
max_value = max(num_tuple)
print(max_value) # Output: 30 (maximum value in the tuple)

5. min():
● The min() function returns the minimum value from a tuple of numbers or the
minimum element based on the default or a specified key function.

● Example:
num_tuple = (10, 20, 5, 30)
min_value = min(num_tuple)
print(min_value) # Output: 5 (minimum value in the tuple)

6. sorted():
● The sorted() function returns a new sorted list from the elements of the tuple. Tuples
themselves are immutable, so a new list is created with the sorted order.

● Example:
my_tuple = (3, 1, 2, 4)
sorted_list = sorted(my_tuple)
print(sorted_list) # Output: [1, 2, 3, 4]

7. any() and all():


● These built-in functions can be used with tuples (or any iterable) to check if any or all
elements satisfy a certain condition.

● Example:
bool_tuple = (True, False, True)
any_true = any(bool_tuple) # Returns True if any element is True
all_true = all(bool_tuple) # Returns False if any element is False

Q. Explain indexing and slicing in list with example.


Ans:
Indexing: An individual item in the list can be referenced by using an index, which is an
integer number that indicates the relative position of the item in the list. There are various
ways in which we can access the elements of a list some as them are given below:

1. List Index: We can use the index operator [] to access an item in a list. Index starts from 0.
So, a list having 5 elements will have index from 0 to 4.

Example: For list index in list.


>>> list1=[10,20,30,40,50]
>>> list1[0]
10
>>> list1[3:] # list[m:] will return elements indexed from mth
index to last index
[40, 50]
>>>list1[:4] # list[:n] will return elements indexed from first
index to n-1th index
[10, 20, 30, 40]
>>> list1[1:3] # list[m:n] will return elements indexed from m
to n-1.
[20, 30]
>>> list1[5]
Traceback (most recent call last):
File "<pyshell#71>", line 1, in <module>
list1[5]
IndexError: list index out of range

2. Negative Indexing: Python allows negative indexing for its sequences. The index of -1
refers to the last item, −2 to the second last item and so on.

Example: For negative indexing in list.


>>> list2=['p','y','t','h','o','n']
>>> list2[-1]
'n'
>>> list2[-6]
'p'
>>> list2[-3:]
['h', 'o', 'n']
>>> list2[-7]
Traceback (most recent call last):
File "<pyshell#76>", line 1, in <module>
list2[-7]
IndexError: list index out of range

3. List Slicing: Slicing is an operation that allows us to extract elements from units. The
slicing feature used by Python to obtain a specific subset or element of the data structure
using the colon (:) operator. The slicing operator returns a subset of a list called slice by
specifying two indices, i.e. start and end.

Syntax: list_variable[start_index:end_index]
This will return the subset of the list starting from start_index to one index less than that of
the ending
Example: For slicing list.
>>> l1=([10,20,30,40,50])
>>> l1[1:4]
[20, 30, 40]
>>>l1[2:5]
[30,40,50]

Q. Write a program to create a dictionary of students that includes their ROLL NO. and
NAME.
i) Add three students in above dictionary
ii) Update name = ‘Shreyas’ of ROLL NO = 2
iii) Delete information of ROLL NO = 1
Ans:
1)
>>> dict1={1:"Vijay",2:"Santosh",3:"Yogita"}
>>>print(dict1)
{1: 'Vijay', 2: 'Santosh', 3: 'Yogita'}

ii)
>>>dict1[2]="Shreyas"
>>>print(dict1)
{1: 'Vijay', 2: 'Shreyas', 3: 'Yogita'}

iii)
>>>dict1.pop(1)
‘Vijay'
>>>print(dict1)
{2: 'Shreyas', 3: 'Yogita'}

Q. Write the output of the following


>>>a=[2,5,1,3,6,9,7]
>>> a[2:6]=[2,4,9,0]
>>> print(a)
Output: [2, 5, 2, 4, 9, 0, 7]

>>> b=["Hello","Good"]
>>> b.append("python")
>>>print(b)
Output: ['Hello', 'Good', 'python']

>>>t1=[3,5,6,7]
>>>print(t1[2])
>>>print(t1[-1])
>>>print(t1[2:])
>>>print(t1[:])
Output:
6
7
[6, 7]
[3, 5, 6, 7]

UNIT 4
Q. Explain Local and Global variable.
Ans:
Local Variables: Local variables are those which are initialized inside a function and belongs
only to that particular function. It cannot be accessed anywhere outside the function.

Example:
def f():
# local variable
s = "I love Python Programming"
print(s)
# Driver code
f()

Output:
I love Python Programming

Global Variables: The global variables are those which are defined outside any function and
which are accessible throughout the program i.e. inside and outside of every function.

Example:
# This function uses global variable s
def f():
print("Inside Function", s)
# Global scope
s = "I love Python Programming"
f()
print("Outside Function", s)

Output:
Inside Function I love Python Programming
Outside Function I love Python Programming

Q. Explain how to use user defined function in python with example.


Ans:
● In Python, you can create user-defined functions to encapsulate a block of reusable
code.
● Functions are defined using the def keyword, followed by the function name and a
pair of parentheses.
● You can also specify parameters inside the parentheses if the function accepts input
values.

Example:
# Define a user-defined function
def greet(name):
"""This function greets the person passed in as a parameter."""
print(f"Hello, {name}!")

# Call the function with an argument


greet("Alice")
greet("Bob")

Parameterized function: The function may take arguments(s) also called parameters as
input within the opening and closing parentheses, just after the function name followed by a
colon.

Syntax:
def function_name(argument1, argument2, ...):
statements
.
.
Example:
def square( x ):
print("Square=",x*x)

# Driver code
square(2)
Output:
Square= 4

Q. Write a program for importing module for addition and subtraction of two numbers.
Ans:
#math_operations.py
def add(a, b):
return a + b

def subtract(a, b):


return a - b
-------------------------------------------------
# Program.py
import math_operations
# Perform addition
result = math_operations.add(10, 5)
print(result) # Output: 15

# Perform subtraction
result = math_operations.subtract(10, 5)
print(result) # Output: 5

Q. Explain use of format() method with example.


Ans:
The format() method formats the specified value(s) and insert them inside the string's placeholder.
The placeholder is defined using curly brackets: {}. The format() method returns the formatted string.

Syntax
string.format(value1, value2...)
Example:
# named indexes:
>>>txt1 = ("My name is {fname}, I'm {age}".format(fname = "abc", age = 36))
>>>print(txt1)
My name is abc, I'm 36
# numbered indexes:
>>>txt2 =( "My name is {0}, I'm {1}".format("xyz",36))
>>>print(txt2)
My name is xyz, I'm 36
# empty placeholders:
>>>txt3 = ("My name is {}, I'm {}".format("pqr",36))
>>>print(txt3)
My name is pqr, I'm 36

Q. Write a program illustrating use of user defined package in python.


Ans:
A package is a hierarchical file directory structure that defines a single Python application
environment that consists of modules and subpackages and sub-subpackages, and so on. Packages
allow for a hierarchical structuring of the module namespace using dot notation. Creating a package is
quite straightforward, since it makes use of the operating system’s inherent hierarchical file structure.

Consider the following arrangement:


Here, there is a directory named pkg that contains two modules, mod1.py and mod2.py. The contents
of the modules are:
mod1.py
def m1():
print("first module")
mod2.py
def m2():
print("second module")

If the pkg directory resides in a location where it can be found, you can refer to the two modules with
dot notation(pkg.mod1, pkg.mod2) and import them with the

Syntax:
Syntax-1
import <module_name>[, <module_name> ...]
Example:
>>>import pkg.mod1, pkg.mod2
>>> pkg.mod1.m1()
first module
Syntax-2:
from <module_name> import <name(s)>
Example:
>>> from pkg.mod1 import m1
>>> m1()
First module
>>>

Syntax-3:
from <module_name> import <name> as <alt_name>
Example:
>>> from pkg.mod1 import m1 as module
>>> module()
first module
You can import modules with these statements as well:
from <package_name> import <modules_name>[,
<module_name> ...]
from <package_name> import <module_name> as <alt_name>
Example:
>>> from pkg import mod1
>>> mod1.m1()
First module

Q. Explain package Numpy with example.


Ans:
● NumPy is the fundamental package for scientific computing with Python. NumPy
stands for "Numerical Python". It provides a high-performance multidimensional
array object, and tools for working with these arrays.
● An array is a table of elements (usually numbers), all of the same type, indexed by a
tuple of positive integers and represented by a single variable. NumPy's array class is
called ndarray. It is also known by the alias array.
● In NumPy arrays, the individual data items are called elements. All elements of an
array should be of the same type. Arrays can be made up of any number of
dimensions.
● In NumPy, dimensions are called axes. Each dimension of an array has a length which
is the total number of elements in that direction.
● The size of an array is the total number of elements contained in an array in all the
dimensions. The size of NumPy arrays are fixed; once created it cannot be changed
again.
● Numpy arrays are great alternatives to Python Lists.Some of the key advantages of
Numpy arrays are that they are fast, easy to work with, and give users the opportunity
to perform calculations across entire arrays.
● A one dimensional array has one axis indicated by Axis-O. That axis has five
elements in it, so we say it has length of five.
● A two dimensional array is made up of rows and columns. All rows are indicated by
Axis-0 and all columns are indicated by Axis-1. Axis-0 in a two dimensional array
has three elements, so its length is three and Axis-1 has six elements, so its length is
six.

Execute Following command to install numpy in window, Linux and MAC OS:
python -m pip install numpy

To use NumPy you need to import Numpy:


import numpy as np # alias np

Using NumPy, a developer can perform the following operations:


1. Mathematical and logical operations on arrays.
2. Fourier transforms and routines for shape manipulation.
3. Operations related to linear algebra.
4. NumPy has in-built functions for linear algebra and random number generation.

Example:

import numpy as np

mat1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])


mat2 = np.array([[9, 8, 7], [6, 5, 4], [3, 2, 1]])

add_result = mat1 + mat2


sub_result = mat1 - mat2
mul_result = mat1 * mat2
div_result = mat1 / mat2

print("Matrix 1:\n", mat1)


print("\nMatrix 2:\n", mat2)
print("\nAddition result:\n", add_result)
print("\nSubtraction result:\n", sub_result)
print("\nMultiplication result:\n", mul_result)
print("\nDivision result:\n", div_result)

UNIT 5

Q. Define class and object in python.


Ans:
Class: A class is a user-defined blueprint or prototype from which objects are created.
Classes provide a means of bundling data and functionality together.
Object: An object is an instance of a class that has some attributes and behavior. Objects can
be used to access the attributes of the class.

Q. Write a program to create class EMPLOYEE with ID and NAME and display its
contents.
Ans:
class Employee:
name = ""
department = ""
salary = 0

def accept(self):
self.name = input("Enter employee name: ")
self.department = input("Enter employee department: ")
self.salary = float(input("Enter employee salary: "))

def display(self):
print("Employee Name:", self.name)
print("Department:", self.department)
print("Salary:", self.salary)

emp = Employee()
emp.accept()
print("\nEmployee Information:")
emp.display()

Q. Explain method overloading in python with example.


Ans:
Method overloading is the ability to define the method with the same name but with a
different number of arguments and data types.
With this ability one method can perform different tasks, depending on the number of
arguments or the types of the arguments given.

Method overloading is a concept in which a method in a class performs operations according


to the parameters passed to it.
As in other languages we can write a program having two methods with same name but with
different number of arguments or order of arguments but in python if we will try to do the
same we will get the following issue with method overloading in Python:
# To calculate area of rectangle
def area(length, breadth):
calc = length * breadth
print calc
#to calculate area of square
def area(size):
calc = size * size
print calc
area(3)
area(4,5)
Output:
9

TypeError: area() takes exactly 1 argument (2 given) Python does not support method
overloading, that is, it is not possible to define more than one method with the same name in
a class in Python.
This is because method arguments in python do not have a type. A method accepting one
argument can be called with an integer value, a string or a double as shown in next example.

class Demo:
def method(self, a):
print(a)
obj= Demo()
obj.method(50)
obj.method('Meenakshi')
obj.method(100.2)
Output:
50
Meenakshi
100.2

Same method works for three different data types. Thus, we cannot define two methods with
the same name and same number of arguments but having different type as shown in the
above example. They will be treated as the same method.
It is clear that method overloading is not supported in python but that does not mean that we
cannot call a method with a different number of arguments. There are a couple of alternatives
available in python that make it possible to call the same method but with different number of
arguments.

Q. Write a program to implement the concept of inheritance in python.


Ans:
● In inheritance objects of one class procure the properties of objects of another class.
● Inheritance provide code usability, which means that some of the new features can be
added to the code while using the existing code.
● The mechanism of designing or constructing classes from other classes is called
inheritance.
● The new class is called derived class or child class and the class from which this
derived class has been inherited is the base class or parent class.
● In inheritance, the child class acquires the properties and can access all the data
members and functions defined in the parent class. A child class can also provide its
specific implementation to the functions of the parent class.

Syntax:
class A:
# properties of class A
class B(A):
# class B inheriting property of class A
# more properties of class B

Example 1: Inheritance without using constructor.


class Vehicle: #parent class
name="Maruti"
def display(self):
print("Name= ",self.name)
class Category(Vehicle): #derived class
price=2000
def disp_price(self):
print("Price=$",self.price)
car1=Category()
car1.display()
car1.disp_price()

Output:
Name= Maruti
Price=$ 2000

Example 2: Inheritance using constructor.


class Vehicle: #parent class
def __init__(self,name):
self.name=name
def display(self):
print("Name= ",self.name)
class Category(Vehicle): #derived class
def __init__(self,name,price):
Vehicle.__init__(self,name)
# passing data to base class constructor
self.price=price
def disp_price(self):
print("Price=$ ",self.price)
car1=Category("Maruti",2000)
car1.display()
car1.disp_price()
car2=Category("BMW",5000)
car2.display()
car2.disp_price()

Output:
Name= Maruti
Price=$ 2000
Name= BMW
Price=$ 5000

UNIT 6

Q. List different modes of opening file in Python.


Ans:
Modes for opening file:
● r: open an existing file for a read operation.
● w: open an existing file for a write operation. If the file already contains some data
then it will be overridden.
● a: open an existing file for append operation. It won’t override existing data.
● r+: To read and write data into the file. The previous data in the file will be
overridden.
● w+: To write and read data. It will override existing data.
● a+: To append and read data from the file. It won’t override existing data.

Q. Write a program to open a file in write mode and append some content at the end of
file.
Ans:
file1 = open("myfile.txt", "w")
L = ["This is Delhi \n", "This is Paris \n", "This is London"]
file1.writelines(L)
file1.close()

# Append-adds at last
# append mode
file1 = open("myfile.txt", "a")

# writing newline character


file1.write("\n")
file1.write("Today")

# without newline character


file1.write("Tomorrow")
file1 = open("myfile.txt", "r")
print("Output of Readlines after appending")
print(file1.read())
print()
file1.close()

Output:
Output of Readlines after appending
This is Delhi
This is Paris
This is London
TodayTomorrow

Q. Explain Try-except block used in exception handling in python with example.


Ans:
● In Python, exceptions can be handled using a try statement. A try block consisting of
one or more statements is used by programmers to partition code that might be
affected by an exception.
● A critical operation which can raise an exception is placed inside the try clause and
the code that handles exception is written in the except clause.
● The associated exception blocks are used to handle any resulting exceptions thrown in
the try block. That is we want the try block to succeed and if it does not succeed, we
want control to pass to the catch block.
● If any statement within the try block throws an exception, control immediately shifts
to the catch block. If no exception is thrown in the try block, the catch block is
skipped.
● There can be one or more except blocks. Multiple except blocks with different
exception names can be chained together.
● The except blocks are evaluated from top to bottom in the code, but only one except
block is executed for each exception that is thrown.
● The first except block that specifies the exact exception name of the thrown exception
is executed. If no except block specifies a matching exception name then an except
block that does not have an exception name is selected, if one is present in the code.
● For handling exceptions in Python, the exception handler block needs to be written
which consists of a set of statements that need to be executed according to raised
exceptions. There are three blocks that are used in the exception handling process,
namely, try,except and finally.

1. try Block: A set of statements that may cause error during runtime are to be written in
the try block.
2. except Block: It is written to display the execution details to the user when a certain
exception occurs in the program. The except block is executed only when a certain
type of exception occurs in the execution of statements written in the try block.
3. finally Block: This is the last block written while writing an exception handler in the
program which indicates the set of statements that many use to clean up resources
used by the program.

Syntax:
try:
Do the operations here
……………..
except Exception1:
If there is Exception1, then execute this block.
except Exception2:
If there is Exception2, then execute this block.
else:
If there is no exception then execute this block.

Example:

try:
# Code that might raise an exception
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
result = num1 / num2
print("Result:", result)

except ZeroDivisionError:
print("Division by zero is not allowed!")

except ValueError:
print("Invalid input. Please enter valid numbers.")

except Exception as e:
print("An error occurred:", e)

else:
print("No exceptions occurred. Goodbye!")

finally:
print("Finally block executed.")

You might also like