Python Unit 2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

Q.

1Attempt any FOUR


A. Define function

Ans. In all programming and scripting language, a function is a block of program statements
which can be used repetitively in a program. It saves the time of a developer. In Python
concept of function is same as in other languages. There are some built-in functions which
are part of Python.

B. Explain the use of lambda expression with example.

Ans. Lambda functions are similar to user-defined functions but without a name. They're
commonly referred to as anonymous functions. Lambda functions are efficient whenever
you want to create a function that will only contain simple expressions – that is, expressions
that are usually a single line of a statement.

For example, if we also want to check if num1 is greater than num2, if num2 is greater
than num1, or else (meaning if they are equal), we can use the following lambda expression:
So if our lambda expression finds that num1 > num2, it will return num1. If this condition is
false, it'll move on to the else statement.

C. Write a program to create bar chart using matplotlib.


Ans.
import matplotlib.pyplot as plt

x_axis = ['value_1', 'value_2', 'value_3', ...]


y_axis = ['value_1', 'value_2', 'value_3', ...]

plt.bar(x_axis, y_axis)
plt.title('title name')
plt.xlabel('x_axis name')
plt.ylabel('y_axis name')
plt.show()

D. Explain Local and Global variable


Ans. Local Variable:-
Local variables are declared inside the function blocks. In Python, local variables can be
declared at any location in the code block. Only statements that are written inside a
function can access local variables. They are secure in the way that no other function or
variable of that program can access them.

Global Variable:-
Global variables are the types of variables that are declared outside of every function of the
program. The global variable, in contrast to local variables, is accessible by all functions in a
program. Global variables are not very reliable because any function in the program can
alter their value.
E. Define class and object in Python
Ans. Class:- A class is a code template for creating objects. Objects have member variables
and have behaviour associated with them. In python a class is created by the keyword class.
An object is created using the constructor of the class. This object will then be called the
instance of the class. In Python we create instances in the following manner.

Object:- An Object is an instance of a Class. A class is like a blueprint while an instance is a


copy of the class with actual values. It's not an idea anymore, it's an actual dog, like a dog of
breed pug who's seven years old.

Q.2Attempt any THREE.

A. Explain following set operations.


i) set union
ii)set intersection
iii) set difference
iv) set symmetric_ifference

Ans. 1. Set Union


The union of two sets is the set of all the elements of both the sets without duplicates. You
can use the union() method or the | syntax to find the union of a Python set.
Example:- first_set = {1, 2, 3}
>>> second_set = {3, 4, 5}
>>> first_set.union(second_set)
{1, 2, 3, 4, 5}
>>>
>>> first_set | second_set # using the | operator
{1, 2, 3, 4, 5}

2. Set Intersection:-
The intersection of two sets is the set of all the common elements of both the sets. You can
use the intersection() method of the & operator to find the intersection of a Python set.
Example:-
>>> first_set = {1, 2, 3, 4, 5, 6}
>>> second_set = {4, 5, 6, 7, 8, 9}
>>> first_set.intersection(second_set)
{4, 5, 6}
>>>
>>> first_set & second_set # using the & operator
{4, 5, 6}

3. Set Difference
The difference between two sets is the set of all the elements in first set that are not
present in the second set. You would use the difference() method or the - operator to
achieve this in Python.
Example:-
>>> first_set = {1, 2, 3, 4, 5, 6}
>>> second_set = {4, 5, 6, 7, 8, 9}
>>> first_set.difference(second_set)
{1, 2, 3}
>>>
>>> first_set - second_set # using the - operator
{1, 2, 3}
>>>
>>> second_set - first_set
{8, 9, 7}

4. Set Symmetric Difference:-


The symmetric difference between two sets is the set of all the elements that are either in
the first set or the second set but not in both. You have the choice of using either the
symmetric_difference() method or the ^ operator to do this in Python.
Example:-
>>> first_set = {1, 2, 3, 4, 5, 6}
>>> second_set = {4, 5, 6, 7, 8, 9}
>>> first_set.symmetric_difference(second_set)
{1, 2, 3, 7, 8, 9}
>>>
>>> first_set ^ second_set # using the ^ operator
{1, 2, 3, 7, 8, 9}

B. Explain any four data conversion functions in python


Ans:- 1) int(a,base)&float():-
 int(a, base): This function converts any data type to an integer. ‘Base’ specifies the
base in which the string is if the data type is a string.
 float(): This function is used to convert any data type to a floating-point number.
Example:- # initializing string

s = "10010"

# printing string converting to int base 2

c = int(s,2)

print ("After converting to integer base 2 : ", end="")

print (c)

# printing string converting to float

e = float(s)

print ("After converting to float : ", end="")

print (e)
2) ord()&hex(),oct():-
ord(): This function is used to convert a character to an integer.
hex(): This function is to convert an integer to a hexadecimal string.
oct(): This function is to convert an integer to an octal string.

Example:- # initializing integer

s = '4'

# printing character converting to integer

c = ord(s)

print ("After converting character to integer : ",end="")

print (c)

# printing integer converting to hexadecimal string

c = hex(56)

print ("After converting 56 to hexadecimal string : ",end="")

print (c)

# printing integer converting to octal string

c = oct(56)

print ("After converting 56 to octal string : ",end="")

print (c)

3) tuple()&set(),list():-
tuple(): This function is used to convert to a tuple.
set(): This function returns the type after converting to set.
list(): This function is used to convert any data.

Example:- # initializing string

s = 'geeks'

# printing string converting to tuple

c = tuple(s)

print ("After converting string to tuple : ",end="")

print (c)
# printing string converting to set

c = set(s)

print ("After converting string to set : ",end="")

print (c)

# printing string converting to list

c = list(s)

print ("After converting string to list : ",end="")

print (c)

C. Explain Python’s built-in module: random.


Ans. Python Random Module:-
Python Random module generates random numbers in Python. These are pseudo-random
numbers means they are not truly random.This module can be used to perform random
actions such as generating random numbers, printing random a value for a list or string, etc.
It is an in-built function in Python. The Python import random module in Python defines a
series of functions for generating or manipulating random integers. Python random() is a
pseudo-random number generator function that generates a random float number between
0.0 and 1.0, is used by functions in the random module.

List of all the functions Python Random Module:-


 seed()-Initialize the random number generator
 getstate()-Returns an object with the current internal state of the random number
generator
 setstate()-Used to restore the state of the random number generator back to the
specified state
 getrandbits()-Return an integer with a specified number of bits

Example 1: Printing a random value from a list in Python.


import random

list1 = [1, 2, 3, 4, 5, 6]

print(random.choice(list1))

Output
3

D. Explain constructor function in python class with example


Ans:- Constructors are generally used for instantiating an object. The task of
constructors is to initialize(assign values) to the data members of the class when an
object of the class is created. In Python the _init_() method is called the constructor
and is always called when an object is created.
Types of constructors :

default constructor: The default constructor is a simple constructor which


doesn’t accept any arguments. Its definition has only one argument which
is a reference to the instance being constructed.

Example of default constructor :

class GeekforGeeks:

# default constructor

def _init_(self):

self.geek = "GeekforGeeks"

# a method for printing data members

def print_Geek(self):

print(self.geek)

# creating object of the class

obj = GeekforGeeks()

# calling the instance method using the object obj


obj.print_Geek()

Output:-
GeekforGeeks

parameterized constructor: constructor with parameters is known as


parameterized constructor. The parameterized constructor takes its first
argument as a reference to the instance being constructed known as self
and the rest of the arguments are provided by the programmer.

Example of the parameterized constructor :

class Addition:

first = 0

second = 0
answer = 0

# parameterized constructor

def _init_(self, f, s):

self.first = f

self.second = s

def display(self):

print("First number = " + str(self.first))

print("Second number = " + str(self.second))

print("Addition of two numbers = " + str(self.answer))

def calculate(self):

self.answer = self.first + self.second

# creating object of the class


# this will invoke parameterized constructor

obj1 = Addition(1000, 2000)

# creating second object of same class

obj2 = Addition(10, 20)

# perform Addition on obj1


obj1.calculate()

# perform Addition on obj2


obj2.calculate()

# display result of obj1


obj1.display()

# display result of obj2


obj2.display()
E. Write a short note on method overloading & method Overriding in Python
Ans: Overloading:-It is a form of Compile time polymorphism. In the case of
method overloading, more than a single method belonging to a single class can
share a similar method name while having different signatures. One can use
method overloading for adding more to the behavior of concerned methods. A
user won’t need more than one class for implementing it. One may or may not
require inheritance in the case of method overloading. One can perform method
overloading between methods that reside within a class.

Overriding:- It is a type of run-time polymorphism. In the case of method


overriding, the child class provides a specific implementation of any method
(that the parent class already provides). Method overriding assists a user in
changing the behavior of already existing methods. One needs at least two
classes to implement it. Inheritance is also a prerequisite in method overriding.
It is because it occurs between both the methods- superclass (parent class)
and child class. Inheritance is a prerequisite in the case of method overriding. One
can perform method overriding between both the methods- child class and parent class
(or superclass).

You might also like