Uploaded by prashant pachani

Python complete papers solution

advertisement
Python
Q.1 What is IDLE & Full Form
Ans:-Integrated Development and Learning Environment.IDLE can be used to execute
a single statement just like Python Shell and also to create, modify, and execute Python
scripts. IDLE provides a fully-featured text editor to create Python script that includes
features like syntax highlighting, autocompletion, and smart indent. It also has a
debugger with stepping and breakpoints features.
Q.2 What is the Use of Matplotlib?
Ans:-Matplotlib is a comprehensive library for creating static, animated, and interactive
visualizations in Python. Matplotlib makes easy things easy and hard things possible.
Create publication quality plots. Make interactive figures that can zoom, pan, update.
Q.3 What is Recursion & Functions
Ans:-Python also accepts function recursion, which means a defined function can call
itself.Recursion is a common mathematical and programming concept. It means that a
function calls itself. This has the benefit of meaning that you can loop through data to
reach a result.
Q.4 Explain Lambda and write all Function Name Using Lambdas
Ans:-A Lambda Function in Python programming is an anonymous function or a
function having no name. It is a small and restricted function having no more than one
line. Just like a normal function, a Lambda function can have multiple arguments with
one expression. Using lambdas with Python built-ins. lambdas in filter() ,lambdas in
map(), lambdas in reduce().
Q.5 What is the use of seek() & tell() method
And:-The tell() method returns the current file position in a file stream. You can change
the current file position with the seek() method.
Q.6 Explain Assertion and Assert statement
Ans:-The assert keyword is used when debugging code.The assert keyword lets you test if a
condition in your code returns True, if not, the program will raise an AssertionError.
Q.7 Explain List of Comprehension
Ans:-List comprehension offers a shorter syntax when you want to create a new list
based on the values of an existing list.
Q.8 What is Tuples & List
Ans:-list and tuple are a class of data structures that can store one or more objects or
values. A list is used to store multiple items in one variable and can be created using
square brackets. Similarly, tuples also can store multiple items in a single variable and
can be declared using parentheses.
Q.9 What is Dictionaries
Ans:-Dictionaries are Python's implementation of a data structure that is more generally
known as an associative array. A dictionary consists of a collection of key-value pairs.
Each key-value pair maps the key to its associated value.
Q.10 What is use of Filter() & Map() Function
Ans:-
MAP()
The map() function in Python takes in a function and a list as an argument. The function
is called with a lambda function and a list and a new list is returned which contains all
the lambda modified items returned by that function for each item.
FILTER()
The filter() function creates a new iterator that filters elements from a previously created
one (like a list, tuple, or dictionary).
The filter() function checks whether or not the given condition is present in the sequence
and then prints the result.
Q.11 Write Syntax for following:
Ans:-
1) Take Integer Input from user
num1 = int(input("Please Enter Number: "))
2) Let data=”Hello”,Print String Data in Reverse Order
data = "Hello"
print(data[::-1])
3) Multiple Comments
"""
This is a comment
written in
more than just one line
"""
4) Declare Tuple with multiple data type elements
my_tuple = ("apple", 1, 2.15, True)
5) Decimal number to octal conversion
decimal_number = 10
octal_number = oct(decimal_number)
print(octal_number)
6) While loop
while expression:
statement(s)
7) Declare global variable
x = "global"
def foo():
global x
x = "local"
foo()
print(x)
Q.12 write any one major difference between following:
Ans:-
1) Mutable and Immutable
The major difference between mutable and immutable objects in Python is that
mutable objects can be modified or changed after their creation but the
immutable objects can not be modified after their creation. This makes immutable
objects final objects.
2) Global and Local
Local variables can only be accessed within the function or module in which they
are defined, in contrast to global variables, which can be used throughout the
entire program. a Global variable can be defined using the global Keyword, also
we can make changes to the variable in the local context.
3) Function and Generator
Generator Functions are memory efficient, as they save a lot of memory while
using generators. A normal function will return a sequence of items, but before
giving the result, it creates a sequence in memory and then gives us the result,
whereas the generator function produces one output at a time.
4) append() and extend()
Appends() It adds an element at the end of the list. The argument passed in the
append function is added as a single element at the end of the list and the length
of the list is increased by 1.
Extend() This method appends each element of the iterable (tuple, string, or list)
to the end of the list and increases the length of the list by the number of
elements of the iterable passed as an argument.
5) readline() and readlines()
readline() reads one line at a time from the file whereas readlines() reads all the
lines at once and returns them as a list of strings
6) Canvas and frame
A Frame is designed to be a parent container of other widgets. A Canvas is like a
canvas that you can draw something on it like lines, circles, text, etc.
7) \d and \D sequence character in regular expression
\d matches any decimal digit whereas \D matches any non-digit character
Q.13 Answer the following questions
Ans:-
1) What is iteration?
Repetitive execution of the same block of code over and over is referred to as
iteration. There are two types of iteration: Definite iteration, in which the number
of repetitions is specified explicitly in advance. Indefinite iteration, in which the
code block executes until some condition is met.
2) What is slicing?
A slice object is used to specify how to slice a sequence. You can specify where
to start the slicing, and where to end. You can also specify the step, which allows
you to e.g. slice only every other item.
3) What is generator?
a generator is a function that returns an iterator that produces a sequence of
values when iterated over. Generators are useful when we want to produce a
large sequence of values, but we don't want to store all of them in memory at
once.
4) How can you convert string to number?
To convert, or cast, a string to an integer in Python, you use the int() built-in
function. The function takes in as a parameter the initial string you want to
convert, and returns the integer equivalent of the value you passed. The general
syntax looks something like this: int("str") .
5) Mention the use of // operator in python?
//
Division (floor): divides the first operand by the second
6) What is the meaning of range function used in for loop?
To loop through a set of code a specified number of times, we can use the
range() function, The range() function returns a sequence of numbers, starting
from 0 by default, and increments by 1 (by default), and ends at a specified
number.
7) How can you find the data type of an object in python?
To determine the type of a variable in Python, use the built-in type() function. In
Python, everything is an object. As a result, when you use the type() function to
print the type of a variable's value to the console, it returns the class type of the
object.
8) What is a mutable object?
Mutable is when something is changeable or has the ability to change. In Python,
‘mutable’ is the ability of objects to change their values. These are often the
objects that store a collection of data.
Q.14 How many types of files in python , write the different operations on
file with example
Ans:Types Of File in Python
There are two types of files in Python and each of them are explained below in detail
with examples for your easy understanding.
They are:
•
Binary file
•
Text file
Python File Handling Operations
Most importantly there are 4 types of operations that can be handled by Python on files:
•
Open
•
Read
•
Write
•
Close
Other operations include:
•
Rename
•
Delete
Python Create and Open a File
Python has an in-built function called open() to open a file.
It takes a minimum of one argument as mentioned in the below syntax. The open
method returns a file object which is used to access the write, read and other in-built
methods.
Syntax:
file_object = open(file_name, mode)
Python Read From File
In order to read a file in python, we must open the file in read mode.
There are three ways in which we can read the files in python.
•
read([n])
•
readline([n])
•
readlines()
Example:
my_file = open(“C:/Documents/Python/test.txt”, “r”)
print(my_file.read(5))
Output:
Hello
Python Write to File
In order to write data into a file, we must open the file in write mode.
We need to be very careful while writing data into the file as it overwrites the content
present inside the file that you are writing, and all the previous data will be erased.
We have two methods for writing data into a file as shown below.
•
write(string)
•
writelines(list)
Example:
my_file = open(“C:/Documents/Python/test.txt”, “w”)
my_file.write(“Hello World”)
Python Append to File
To append data into a file we must open the file in ‘a+’ mode so that
we will have access to both the append as well as write modes.
Example :
my_file = open(“C:/Documents/Python/test.txt”, “a+”)
my_file.write (“Strawberry”)
my_file.close()
Python Close File
In order to close a file, we must first open the file. In python,
We have an in-built method called close() to close the file which is opened. Whenever
you open a file, it is important to close it, especially with the write method. Because if we
don’t call the close function after the write method then whatever data we have written
to a file will not be saved into the file.
Example:
my_file = open(“C:/Documents/Python/test.txt”, “r”)
print(my_file.read())
my_file.close()
remove() method:
We use the remove() method to delete the file by supplying the file name or the file
location that you want to delete.
Syntax:
os.remove(file_name)
Example:
import os
os.remove(“test.txt”)
Writing and Reading Data from a Binary File
Binary files store data in the binary format (0’s and 1’s) which is
understandable by the machine.
So when we open the binary file in our machine, it decodes the
data and displays in a human-readable format.
Example:
#Let’s create some binary files.
my_file = open(“C:/Documents/Python/bfile.bin”, “wb+”)
message = “Hello Python”
file_encode = message.encode(“ASCII”)
my_file.write(file_encode)
my_file.seek(0)
bdata = my_file.read()
print(“Binary Data:”, bdata)
ntext = bdata.decode(“ASCII”)
print(“Normal data:”, ntext)
In the above example, first we are creating a binary file ‘bfile.bin’ with the read and write
access and whatever data you want to enter into the file must be encoded before you
call the write method.
OR
File Handling in Python - GeeksforGeeks
Q.15 What is a data frame? Write different operation on file with example
Ans:- Python Pandas DataFrame - GeeksforGeeks
Q.16 Explain various types of variable & method in class
Ans:-In Python, a class is a blueprint for creating objects. A class can have two types of
variables: instance variables and class variables.
Instance variables are unique to each instance of the class, while class variables are
shared among all instances of the class.
A class can have two types of methods: instance method and class method.
Instance method: Used to access or modify the object state. If we use instance
variables inside a method, such methods are called instance methods. It must have a
self parameter to refer to the current object.
Class method: Used to access or modify the class state. In method implementation, if
we use only class variables, then such types of methods we should declare as a class
method. The class method has a cls parameter which refers to the class
Here’s an example:
class Car:
# Class variable
wheels = 4
def __init__(self, make, model):
# Instance variables
self.make = make
self.model = model
# Instance method
def get_make_and_model(self):
return f"{self.make} {self.model}"
# Class method
@classmethod
def get_wheels(cls):
return cls.wheels
my_car = Car("Toyota", "Corolla")
print(my_car.get_make_and_model()) # Output: Toyota Corolla
print(Car.get_wheels()) # Output: 4
In this example, wheels is a class variable because it is shared among all instances of
the Car class. make and model are instance variables because they are unique to each
instance of the Car class.
There are also two types of methods in Python classes: instance methods and class
methods. Instance methods are called on an instance of the class and have access to
the instance’s attributes. Class methods are called on the class itself and have access
to the class’s attributes.
Q.17 Explain various block of exception handling with example
Ans:-When a Python program meets an error, it stops the execution of the rest of the program.
An error in Python might be either an error in the syntax of an expression or a Python exception.
An exception in Python is an incident that happens while executing a program that causes the
regular course of the program's commands to be disrupted. When a Python code comes across
a condition it can't handle, it raises an exception. An object in Python that describes an error is
called an exception.
Example
1.
string = "Python Exceptions"
2.
for s in string:
3.
if (s != o:
4.
print( s )
Output:
if (s != o:
^
SyntaxError: invalid syntax
Try and Except Statement - Catching Exceptions
We catch exceptions and handle them using try and except code blocks. The try clause contains
the code that can raise an exception, while the except clause contains the code lines that
handle the exception.
Example
# Python code to catch an exception and handle it using try and except code blocks
a = ["Python", "Exceptions", "try and except"]
try:
#looping through the elements of the array a, choosing a range that goes beyond the
length of the array
for i in range( 4 ):
print( "The index and element from the array is", i, a[i] )
#if an error occurs in the try block, then except block will be executed by the Python
interpreter
except:
print ("Index out of range")
Output:
The index and element from the array is 0 Python
The index and element from the array is 1 Exceptions
The index and element from the array is 2 try and except
Index out of range
Finally Keyword in Python
The finally keyword is available in Python, and it is always used after the try-except block. The
finally code block is always executed after the try block has terminated normally or after the try
block has terminated for some other reason.
Example
# Python code to show the use of finally clause
# Raising an exception in try block
try:
div = 4 // 0
print( div )
# this block will handle the exception raised
except ZeroDivisionError:
print( "Attempting to divide by zero" )
# this will always be executed no matter exception is raised or not
finally:
print( 'This is code of finally clause' )
Output:
Attempting to divide by zero
This is code of finally clause
OR
Python Exception Handling - GeeksforGeeks
Q.18 Explain Recursion. Write a program to find factorials with iterative and
recursive methods.
Ans:-Recursion is a technique in programming where a function calls itself to solve a problem.
In Python, recursion can be used to solve problems that can be broken down into smaller
sub-problems. Recursive functions make the code look clean and elegant, and a complex task
can be broken down into simpler sub-problems using recursion. However, sometimes the
recursive approach can be slower than an iterative approach and can lead to stack overflow
errors if the recursion depth is too large.
In Python, we can use recursion to find the factorial of a number. Here is an example of how to
find the factorial of a number using both iterative and recursive functions in Python:
Example
# Iterative function to find factorial of a number
def factorial_iterative(n):
fact = 1
for i in range(1,n+1):
fact = fact * i
return fact
# Recursive function to find factorial of a number
def factorial_recursive(n):
if n == 1:
return n
else:
return n*factorial_recursive(n-1)
num = int(input("Enter a number: "))
print("Factorial using iterative method:",factorial_iterative(num))
print("Factorial using recursive method:",factorial_recursive(num))
Q.19 Explain module? How to create our own module in python
Ans:- A module is a self-contained Python file that contains Python statements and definitions,
like a file named moduleex.py, can be considered as a module named moduleex which can be
imported with the help of import statement. However, one might get confused about the
difference between modules and packages. A package is a collection of modules in directories
that give structure and hierarchy to the modules.
Creating and Importing a module
A module is simply a Python file with a .py extension that can be imported inside another Python
program. The name of the Python file becomes the module name. The module contains
definitions and implementation of classes, variables, and functions that can be used inside
another program.
Example
File 1:
''' moduleex.py '''
# Python program to create
# a module
# Defining a function
def Greets():
print("hello")
# Defining a variable
location = "Noida"
File 2:
# Python program to demonstrate
# modules
import moduleex
# Use the function created
moduleex.Greets()
# Print the variable declared
print(moduleex.location)
Q.20 Explain Anonymous function and filter(),map() and reduce() function
using lambda with example
Ans:Using Lambda Function with filter()
The filter() method accepts two arguments in Python: a function and an iterable such as
a list.
The function is called for every item of the list, and a new iterable or list is returned that
holds just those elements that returned True when supplied to the function.
Here's a simple illustration of using the filter() method to return only odd numbers from a
list.
Code
# Code to filter odd numbers from a given list
list_ = [34, 12, 64, 55, 75, 13, 63]
odd_list = list(filter( lambda num: (num % 2 != 0) , list_ ))
print(odd_list)
Output:
[55, 75, 13, 63]
Using Lambda Function with map()
A method and a list are passed to Python's map() function.
The function is executed for all of the elements within the list, and a new list is produced
with elements generated by the given function for every item.
The map() method is used to square all the entries in a list in this example.
Code
#Code to calculate the square of each number of a list using the map() function
numbers_list = [2, 4, 5, 1, 3, 7, 8, 9, 10]
squared_list = list(map( lambda num: num ** 2 , numbers_list ))
print( squared_list )
Output:
[4, 16, 25, 1, 9, 49, 64, 81, 100]
Using Lambda Function with reduce()
The reduce() function in Python takes in a function and a list as an argument. The
function is called with a lambda function and an iterable and a new reduced result is
returned. This performs a repetitive operation over the pairs of the iterable. The reduce()
function belongs to the functools module.
# Python code to illustrate
# reduce() with lambda()
# to get sum of a list
from functools import reduce
li = [5, 8, 10, 20, 50, 100]
sum = reduce((lambda x, y: x + y), li)
print(sum)
Output:
193
Q.21 What is a regular expression? Explain
Regular Expression in Python with Examples | Set 1 - GeeksforGeeks
Q.22 explain sequence character, quantifiers and sequence characters in
regular expressions? Explain using examples.
ANS:-In regular expressions, quantifiers match the preceding characters or
character sets a number of times. A quantifier has the form {m,n} where m and n
are the minimum and maximum times the expression to which the quantifier
applies must match. We can use quantifiers to specify the number of occurrences
to match. Here are some examples:
MetaCharacters
\
Description
Used to drop the special meaning of
character following it
[]
Represent a character class
^
Matches the beginning
$
Matches the end
.
Matches any character except newline
|
?
*
+
{}
()
Means OR (Matches with any of the
characters separated by it.
Matches zero or one occurrence
Any number of occurrences (including 0
occurrences)
One or more occurrences
Indicate the number of occurrences of a
preceding regex to match.
Enclose a group of Regex
Sequence characters are special characters that represent a sequence of
characters. Here are some examples:
Special
Sequence
Description
Examples
for
geeks
\A
Matches if the string begins with
the given character
\Afor
for the
world
Matches if the word begins or
geeks
ends with the given character.
\b
\b(string) will check for the
beginning of the word and
\bge
(string)\b will check for the
get
ending of the word.
together
It is the opposite of the \b i.e. the
\B
string should not start or end
\Bge
with the given regex.
forge
123
\d
Matches any decimal digit, this is
equivalent to the set class [0-9]
\d
gee1
geeks
Matches any non-digit character,
\D
this is equivalent to the set class
\D
[^0-9]
geek1
gee ks
\s
Matches any whitespace
character.
\s
a bc a
a bd
\S
Matches any non-whitespace
character
\S
abcd
123
Matches any alphanumeric
\w
character, this is equivalent to the
\w
class [a-zA-Z0-9_].
geeKs4
>$
\W
Matches any non-alphanumeric
character.
\W
gee<>
abcdab
\Z
Matches if the string ends with
the given regex
ab\Z
ababab
ab
Here’s an example of how you can use quantifiers and sequence characters in
Python:
import re
text = "The quick brown fox jumps over the lazy dog."
pattern = r"\b\w{4}\b"
matches = re.findall(pattern, text)
print(matches) # Output: ['quick', 'brown', 'jumps', 'over', 'lazy']
In this example, we’re using the \b sequence character to match word boundaries
and the {4} quantifier to match words that are exactly four characters long.
OR
Regular Expression in Python with Examples | Set 1 - GeeksforGeeks
Q.23 What is data visualization?explain bar graph and histogram with
example
What is data visualization
Data visualization is a field in data analysis that deals with visual representation
of data. It graphically plots data and is an effective way to communicate
inferences from data.
Using data visualization, we can get a visual summary of our data. With pictures,
maps and graphs, the human mind has an easier time processing and
understanding any given data. Data visualization plays a significant role in the
representation of both small and large data sets, but it is especially useful when
we have large data sets, in which it is impossible to see all of our data, let alone
process and understand it manually.
Data Visualization in Python
Python offers several plotting libraries, namely Matplotlib, Seaborn and many
other such data visualization packages with different features for creating
informative, customized, and appealing plots to present data in the most simple
and effective way
Bar Plot in Matplotlib
A bar plot or bar chart is a graph that represents the category of data with
rectangular bars with lengths and heights that is proportional to the values which
they represent. The bar plots can be plotted horizontally or vertically. A bar chart
describes the comparisons between the discrete categories. One of the axes of
the plot represents the specific categories being compared, while the other axis
represents the measured values corresponding to those categories.
Creating a bar plot
The matplotlib API in Python provides the bar() function which can be used in
MATLAB style use or as an object-oriented API. The syntax of the bar() function
to be used with the axes is as follows:plt.bar(x, height, width, bottom, align)
The function creates a bar plot bounded with a rectangle depending on the given
parameters. Following is a simple example of the bar plot, which represents the
number of students enrolled in different courses of an institute.
import numpy as np
import matplotlib.pyplot as plt
# creating the dataset
data = {'C':20, 'C++':15, 'Java':30, 'Python':35}
courses = list(data.keys())
values = list(data.values())
fig = plt.figure(figsize = (10, 5))
# creating the bar plot
plt.bar(courses, values, color ='maroon',width = 0.4)
plt.xlabel("Courses offered")
plt.ylabel("No. of students enrolled")
plt.title("The number of Students enrolled in different courses of an institute.")
plt.show()
Output-
Histogram
In Matplotlib, we use the hist() function to create histograms.
The hist() function will use an array of numbers to create a histogram, the array is
sent into the function as an argument.
For simplicity we use NumPy to randomly generate an array with 250 values,
where the values will concentrate around 170, and the standard deviation is 10.
Example
import matplotlib.pyplot as plt
import numpy as np
x = np.random.normal(170, 10, 250)
plt.hist(x)
plt.show()
#Two lines to make our compiler able to draw:
plt.savefig(sys.stdout.buffer)
sys.stdout.flush()
Output
Q.24 explain function decorators and generators with examples
Generator-Function: A generator-function is defined like a normal function, but
whenever it needs to generate a value, it does so with the yield keyword rather
than return. If the body of a def contains yield, the function automatically
becomes a generator function.
# A generator function that yields 1 for first time,
# 2 second time and 3 third time
def simpleGeneratorFun():
yield 1
yield 2
yield 3
# Driver code to check above generator function
for value in simpleGeneratorFun():
print(value)
Output
1
2
3
Decorators are a very powerful and useful tool in Python since it allows
programmers to modify the behavior of a function or class. Decorators allow us to
wrap another function in order to extend the behavior of the wrapped function,
without permanently modifying it.
Example:def outer(x):
def inner(y):
return x + y
return inner
add_five = outer(5)
result = add_five(6)
print(result) # prints 11
# Output: 11
Q.25 What is a dictionary in python?explain with an example
Dictionary in Python is a collection of keys values, used to store data values like
a map, which, unlike other data types which hold only a single value as an
element.
Creating a Dictionary
In Python, a dictionary can be created by placing a sequence of elements within
curly {} braces, separated by ‘comma’. Dictionary holds pairs of values, one
being the Key and the other corresponding pair element being its Key:value.
Values in a dictionary can be of any data type and can be duplicated, whereas
keys can’t be repeated and must be immutable.
Note – Dictionary keys are case sensitive, the same name but different cases of
Key will be treated distinctly.
Example
# Creating a Dictionary
# with Integer Keys
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)
# Creating a Dictionary
# with Mixed keys
Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)
Output:
Dictionary with the use of Integer Keys:
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Dictionary with the use of Mixed Keys:
{'Name': 'Geeks', 1: [1, 2, 3, 4]}
Q.26 compare list,tuple and dictionary data type.
Differences and Applications of List, Tuple, Set and Dictionary in Python GeeksforGeeks
Q.27 Explain following method of pyplot with example
1. hist()
In Matplotlib, we use the hist() function to create histograms.
The hist() function will use an array of numbers to create a histogram, the
array is sent into the function as an argument.
For simplicity we use NumPy to randomly generate an array with 250
values, where the values will concentrate around 170, and the standard
deviation is 10.
Example
import matplotlib.pyplot as plt
import numpy as np
x = np.random.normal(170, 10, 250)
plt.hist(x)
plt.show()
#Two lines to make our compiler able to draw:
plt.savefig(sys.stdout.buffer)
sys.stdout.flush()
output
2. pie()
The pie() function in the pyplot module of matplotlib is used to create a pie
chart representing the data in an array.
The best pie chart can be created if the figure and axes are square, or the
aspect of the Axes is equal.
Example
import matplotlib.pyplot as plt
import numpy as np
y = np.array([35, 25, 25, 15])
plt.pie(y)
plt.show()
#Two lines to make our compiler able to draw:
plt.savefig(sys.stdout.buffer)
sys.stdout.flush()
output
3. title()
you can use the title() function to set a title for the plot. Matplotlib titles are
the titles of 2D graphs plotted using matplotlib.pyplot. They are used to
name the graphs for identification and explanation purposes. We can also
alter the title's color, size, font, location, alignment, etc., using the
pyplot.title() function.
Example
# importing module
import matplotlib.pyplot as plt
# assigning x and y coordinates
y = [0,1,2,3,4,5]
x= [0,5,10,15,20,25]
# depicting the visualization
plt.plot(x, y, color='green')
plt.xlabel('x')
plt.ylabel('y')
# displaying the title
plt.title("Linear graph")
plt.show()
Output
Q.28 Explain seek() and tell() method in detail with proper example to read
binary file
Access modes govern the type of operations possible in the opened file. It refers
to how the file will be used once it’s opened. These modes also define the
location of the File Handle in the file. File handle is like a cursor, which defines
from where the data has to be read or written in the file. Sometimes it becomes
important for us to know the position of the File Handle.
tell() method:
tell() method can be used to get the position of File Handle. tell() method returns
current position of file object. This method takes no parameters and returns an
integer value. Initially the file pointer points to the beginning of the file(if not
opened in append mode). So, the initial value of tell() is zero.
syntax :
file_object.tell()
Example
For binary files. Let’s create a binary file and we will notice the position of the
handle before writing and after writing to binary file.
# Python program to demonstrate
# tell() method
# for reading binary file we
# have to use "wb" in file mode.
fp = open("sample2.txt", "wb")
print(fp.tell())
# Writing to file
fp.write(b'1010101')
print(fp.tell())
# Closing file
fp.close()
Output :
0
7
seek() method
In Python, seek() function is used to change the position of the File Handle to a
given specific position. File handle is like a cursor, which defines from where the
data has to be read or written in the file.
Syntax: f.seek(offset, from_what), where f is file pointer
Parameters:
Offset: Number of positions to move forward
from_what: It defines a point of reference.
Returns: Return the new absolute position.
Example
Seek() function with negative offset only works when a file is opened in binary
mode. Let’s suppose the binary file contains the following text.
b'Code is like humor. When you have to explain it, its bad.'
# Python code to demonstrate
# use of seek() function
# Opening "GfG.txt" text file
# in binary mode
f = open("data.txt", "rb")
# sets Reference point to tenth
# position to the left from end
f.seek(-10, 2)
# prints current position
print(f.tell())
# Converting binary to string and printing
print(f.readline().decode('utf-8'))
f.close()
Output:
47
, its bad.
Q.29 What is inheritance? What are the different type of inheritance
available in python
Inheritance provides code reusability to the program because we can use an
existing class to create a new class instead of creating it from scratch.
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.
In python, a derived class can inherit base class by just mentioning the base in
the bracket after the derived class name. Consider the following syntax to inherit
a base class into the derived class.
Syntax
1.
class derived-class(base class):
2.
<class-suite>
Types of Inheritance in Python
The types of inheritance depend on the number of children and parents involved.
There are four kinds of inheritance available in Python:
Single Inheritance
Single inheritance allows a derived class to inherit properties of one parent class,
and this allows code reuse and the introduction of additional features in existing
code.
Example:
# Python program for demonstrating single inheritance
# Here, we will create the base class or the Parent class
class Parent1:
def func_1(self):
print ("This function is defined inside the parent class.")
# now, we will create the Derived class
class Child1(Parent1):
def func_2(self):
print ("This function is defined inside the child class.")
# Driver's code
object = Child1()
object.func_1()
object.func_2()
Output:
This function is defined inside the parent class.
This function is defined inside the child class.
Multiple Inheritance If a class is able to be created from multiple base classes, this
kind of Inheritance is known as multiple Inheritance. When there is multiple Inheritance,
each of the attributes that are present in the classes of the base has been passed on to
the class that is derived from it.
Example:
# Python program for demonstrating multiple inheritance
# Here, we will create the Base class 1
class Mother1:
mothername1 = " "
def mother1(self):
print(self.mothername1)
# Here, we will create the Base class 2
class Father1:
fathername1 = " "
def father1(self):
print(self.fathername1)
# now, we will create the Derived class
class Son1(Mother1, Father1):
def parents1(self):
print ("Father name is :", self.fathername1)
print ("Mother name is :", self.mothername1)
# Driver's code
s1 = Son1()
s1.fathername1 = "Rajesh"
s1.mothername1 = "Shreya"
s1.parents1()
Output:
Father name is : Rajesh
Mother name is : Shreya
Multilevel inheritance, the features that are part of the original class, as well as the
class that is derived from it, are passed on to the new class. It is similar to a relationship
involving grandparents and children.
Example:
# Python program for demonstrating multilevel inheritance
# Here, we will create the Base class
class Grandfather1:
def __init__(self, grandfathername1):
self.grandfathername1 = grandfathername1
# here, we will create the Intermediate class
class Father1(Grandfather1):
def __init__(self, fathername1, grandfathername1):
self.fathername1 = fathername1
# here, we will invoke the constructor of Grandfather class
Grandfather1.__init__(self, grandfathername1)
# here, we will create the Derived class
class Son1(Father1):
def __init__(self,sonname1, fathername1, grandfathername1):
self.sonname1 = sonname1
# here, we will invoke the constructor of Father class
Father1.__init__(self, fathername1, grandfathername1)
def print_name(self):
print('Grandfather name is :', self.grandfathername1)
print("Father name is :", self.fathername1)
print("Son name is :", self.sonname1)
# Driver code
s1 = Son1('John', 'John Jr', 'John Jr Jr')
print (s1.grandfathername1)
s1.print_name()
Output:
John Jr Jr
Grandfather name is : John Jr Jr
Father name is : John Jr
Son name is : John
Hierarchical Inheritance If multiple derived classes are created from the same
base, this kind of Inheritance is known as hierarchical inheritance. In this
instance, we have two base classes as a parent (base) class as well as two
children (derived) classes.
Example:
1.
# Python program for demonstrating Hierarchical inheritance
2.
3.
# Here, we will create the Base class
4.
class Parent1:
5.
def func_1(self):
6.
print ("This function is defined inside the parent class.")
7.
8.
# Derived class1
9.
class Child_1(Parent1):
10.
def func_2(self):
11.
print ("This function is defined inside the child 1.")
12.
13. # Derivied class2
14. class Child_2(Parent1):
15.
def func_3(self):
16.
print ("This function is defined inside the child 2.")
17.
18. # Driver's code
19. object1 = Child_1()
20. object2 = Child_2()
21. object1.func_1()
22. object1.func_2()
23. object2.func_1()
24. object2.func_3()
Output:
This function is defined inside the parent class.
This function is defined inside the child 1.
This function is defined inside the parent class.
This function is defined inside the child 2.
Hybrid Inheritance:
Inheritance consisting of multiple types of inheritance is called hybrid inheritance.
Example:
# Python program to demonstrate
# hybrid inheritance
class School:
def func1(self):
print("This function is in school.")
class Student1(School):
def func2(self):
print("This function is in student 1. ")
class Student2(School):
def func3(self):
print("This function is in student 2.")
class Student3(Student1, School):
def func4(self):
print("This function is in student 3.")
# Driver's code
object = Student3()
object.func1()
object.func2()
Output:
This function is in school.
This function is in student 1.
Q.30 Explain user defined exception with example
Exceptions need to be derived from the Exception class, either directly or
indirectly. Although not mandatory, most of the exceptions are named as names
that end in “Error” similar to the naming of the standard exceptions in python.
# define Python user-defined exceptions
class InvalidAgeException(Exception):
"Raised when the input value is less than 18"
pass
# you need to guess this number
number = 18
try:
input_num = int(input("Enter a number: "))
if input_num < number:
raise InvalidAgeException
else:
print("Eligible to Vote")
except InvalidAgeException:
print("Exception occurred: Invalid Age")
OR
User-defined Exceptions in Python with Examples GeeksforGeeks
Q.31 Explain list,tuple and dictionary data type
List
A list in Python is used to store the sequence of various types of data. A list can
be defined as a collection of values or items of different types. Python lists are
mutable types which implies that we may modify its element after it has been
formed. The items in the list are separated with the comma (,) and enclosed with
the square brackets [].
Although Python has six data types that may hold sequences, the list is the most
popular and dependable form. The collection of data is stored in a list, a
sequence data type. Similar sequence data formats are Tuples and String.
Python lists are identical to dynamically scaled arrays that are specified in other
languages, such as Java's ArrayList and C++'s vector. A list is a group of items
that are denoted by the symbol [] and subdivided by commas.
List Declaration
Example
# a simple list
list1 = [1, 2, "Python", "Program", 15.9]
list2 = ["Amy", "Ryan", "Henry", "Emma"]
# printing the list
print(list1)
print(list2)
# printing the type of list
print(type(list1))
print(type(list2))
Output:
[1, 2, 'Python', 'Program', 15.9]
['Amy', 'Ryan', 'Henry', 'Emma']
< class ' list ' >
< class ' list ' >
Tuples
A Python Tuple is a group of items that are separated by commas. The indexing,
nested objects, and repetitions of a tuple are somewhat like those of a list,
however unlike a list, a tuple is immutable.
The distinction between the two is that while we can edit the contents of a list, we
cannot alter the elements of a tuple once they have been assigned.
Example
("Suzuki", "Audi", "BMW"," Skoda ") is a tuple.
Creating of Tuple:
To create a tuple, all the objects (or "elements") must be enclosed in parenthesis
(), each one separated by a comma. Although it is not necessary to include
parentheses, doing so is
A tuple can contain any number of items, including ones with different data types
(dictionary, string, float, list, etc.).
Example:
# Python program to show how to create a tuple
# Creating an empty tuple
empty_tuple = ()
print("Empty tuple: ", empty_tuple)
# Creating tuple having integers
int_tuple = (4, 6, 8, 10, 12, 14)
print("Tuple with integers: ", int_tuple)
# Creating a tuple having objects of different data types
mixed_tuple = (4, "Python", 9.3)
print("Tuple with different data types: ", mixed_tuple)
# Creating a nested tuple
nested_tuple = ("Python", {4: 5, 6: 2, 8:2}, (5, 3, 5, 6))
print("A nested tuple: ", nested_tuple)
Output:
Empty tuple: ()
Tuple with integers: (4, 6, 8, 10, 12, 14)
Tuple with different data types: (4, 'Python', 9.3)
A nested tuple: ('Python', {4: 5, 6: 2, 8: 2}, (5, 3, 5, 6))
Dictionary
Dictionaries are a useful data structure for storing data in Python because they
are capable of imitating real-world data arrangements where a certain value
exists for a given key.
The data is stored as key-value pairs using a Python dictionary.
This data structure is mutable
The components of the dictionary were made using keys and values.
Keys must only have one component.
Values can be of any type, including integer, list, and tuple.
A dictionary is, in other words, a group of key-value pairs, where the values can
be any Python object. The keys, in contrast, are immutable Python objects, such
as strings, tuples, or numbers. Dictionary entries are ordered as of Python
version 3.7. In Python 3.6 and before, dictionaries are generally unordered.
Creating the Dictionary
Curly brackets are the simplest way to generate a Python dictionary, although
there are other approaches as well. With many key-value pairs surrounded in
curly brackets and a colon separating each key from its value, the dictionary can
be built. (:). The following provides the syntax for defining the dictionary.
Syntax:
Dict = {"Name": "Gayle", "Age": 25}
In the above dictionary Dict, The keys Name and Age are the strings which
comes under the category of an immutable object.
Let's see an example to create a dictionary and print its content.
Example
Employee = {"Name": "Johnny", "Age": 32, "salary":26000,"Company":"^TCS"}
print(type(Employee))
print("printing Employee data .... ")
print(Employee)
Output
<class 'dict'>
printing Employee data ....
{'Name': 'Johnny', 'Age': 32, 'salary': 26000, 'Company': TCS}
Python provides the built-in function dict() method which is also used to create
the dictionary.
The empty curly braces {} is used to create empty dictionary.
Q.32 Explain Abstract data type and classes
Abstract data type
The abstract data type is a special kind of data type, whose behavior is defined
by a set of values and set of operations. The keyword “Abstract” is used as we
can use these data types, we can perform different operations. But how those
operations are working is totally hidden from the user. The ADT(Abstract Data
Type) is made of primitive data types, but operation logics are hidden.
Abstract classes
An abstract class can be considered as a blueprint for other classes. It allows
you to create a set of methods that must be created within any child classes built
from the abstract class. A class which contains one or more abstract methods is
called an abstract class. An abstract method is a method that has a declaration
but does not have an implementation. While we are designing large functional
units we use an abstract class. When we want to provide a common interface for
different implementations of a component, we use an abstract class.
Example
# Python program showing
# abstract base class work
from abc import ABC, abstractmethod
class Polygon(ABC):
@abstractmethod
def noofsides(self):
pass
class Triangle(Polygon):
# overriding abstract method
def noofsides(self):
print("I have 3 sides")
class Pentagon(Polygon):
# overriding abstract method
def noofsides(self):
print("I have 5 sides")
class Hexagon(Polygon):
# overriding abstract method
def noofsides(self):
print("I have 6 sides")
class Quadrilateral(Polygon):
# overriding abstract method
def noofsides(self):
print("I have 4 sides")
# Driver code
R = Triangle()
R.noofsides()
K = Quadrilateral()
K.noofsides()
R = Pentagon()
R.noofsides()
K = Hexagon()
K.noofsides()
Output:
I have 3 sides
I have 4 sides
I have 5 sides
I have 6 sides
Q.33 what is indexing and slicing. explain it with example
index()
The list index() method helps you to find the first lowest index of the given
element. If there are duplicate elements inside the list, the first index of the
element is returned. This is the easiest and straightforward way to get the index.
Besides the built-in list index() method, you can also use other ways to get the
index like looping through the list, using list comprehensions, enumerate(), filter
methods.
The list index() method returns the first lowest index of the given element.
Syntax
list.index(element, start, end)
Parameters
Parameters
Description
element
The element that you want to get the index.
start
This parameter is optional. You can define the start: index to
search for the element. If not given, the default value is 0.
end
This parameter is optional. You can specify the end index for
the element to be searched. If not given, it is considered until the end of the list.
Example
my_list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
print("The index of element C is ", my_list.index('C', 1, 5))
print("The index of element F is ", my_list.index('F', 3, 7))
#using just the startindex
print("The index of element D is ", my_list.index('D', 1))
Output:
The index of element C is 2
The index of element F is 5
The index of element D is 3
slicing()
The slice() function returns a slice object.
A slice object is used to specify how to slice a sequence. You can specify where
to start the slicing, and where to end. You can also specify the step, which allows
you to e.g. slice only every other item.
Syntax
slice(start, end, step)
Parameter Values
Parameter Description
start
Optional. An integer number specifying at which position to start the
slicing. Default is 0
end
An integer number specifying at which position to end the slicing
step
Optional. An integer number specifying the step of the slicing.
Default is 1
Example
a = ("a", "b", "c", "d", "e", "f", "g", "h")
x = slice(0, 8, 3)
print(a[x])
Output
('a', 'd', 'g')
Q.34 Explain iteration mechanism with real life example of WHILE and
FOR
ANS:-Python language provides the following types of loops to handle looping
requirements.
While Loop in Python
In python, a while loop is used to execute a block of statements repeatedly until a
given condition is satisfied. And when the condition becomes false, the line
immediately after the loop in the program is executed.
Syntax:
while expression:
statement(s)
All the statements indented by the same number of character spaces after a
programming construct are considered to be part of a single block of code.
Python uses indentation as its method of grouping statements.
example:
i=1
while i <= 5:
print(i)
i += 1
In this example, we use a while loop to print the numbers from 1 to 5. The loop
continues as long as the value of i is less than or equal to 5. The value of i is
incremented by 1 after each iteration.
For Loop in Python
For loops are used for sequential traversal. For example: traversing a list or
string or array etc. In Python, there is a “for in” loop which is similar to for each
loop in other languages. Let us learn how to use for in loop for sequential
traversals.
Syntax:
for iterator_var in sequence:
statements(s)
example
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
In this example, we use a for loop to iterate over the list of fruits and print each
fruit on a new line.
Both while and for loops can be used to repeat a set of instructions multiple
times. However, they are used in different situations. A while loop is used when
you don’t know how many times you need to repeat the instructions, while a for
loop is used when you know how many times you need to repeat the instructions
(such as when iterating over a sequence)
Q.35 Explain branching in python with example
Branching is the process of using conditions to determine which set of
instructions to execute. If a certain condition is met, the python program will
execute one set of instructions, and if the condition is not met, it will execute a
different set of instructions.
1) if statements
We can use an if statement to evaluate a comparison. We start with the if
keyword, followed by our comparison. We end the line with a colon. The body of
the if statement is then indented to the right.
if condition:
# Statements to execute if
# condition is true
Example
# Example: Checking a condition using only if
x = 10
if x > 5:
print("x is greater than 5")
# Output: x is greater than 5
If the comparison is True, the code inside the if body is executed. If the
comparison evaluates to False, then the code block is skipped and will not be
run.
But what if we wanted the code to do something different if the evaluation is
false? We can do this using the else statement.
2) if-else statements
The else statement follows an if block and is composed of the keyword else
followed by a colon. The body of the else statement is indented to the right and
will be executed if the above if statement doesn’t execute.
if condition:
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false
A simple example of if-else to check if a number is positive or not is shown
below:
number = int(input(“enter the number”)) #We have typecasted string to integer
if number > 0:
print("POSITIVE NUMBER")
else:
print("ZERO OR NEGATIVE NUMBER")
3) nested if statements
A nested if is an if statement that is the target of another if statement. Nested if
statements mean an if statement inside another if statement.
if condition1:
# Executes when condition1 is true
if condition2:
# Executes when condition2 is true
# if Block is ending here
# if Block is ending here
# Example: Nested if block
x = 10
y=5
if x > 5:
print("x is greater than 5")
if y > 0:
print("y is positive")
else:
print("y is non-positive")
# Output:
# x is greater than 5
# y is positive
4) if-elif-else statements
Very similar to the if statements, an elif statement starts with the elif keyword,
followed by a comparison to be evaluated. This is followed by a colon, and then
the code block on the next line, indented to the right.
An elif statement must follow an if statement, and will only be evaluated if the if
statement was evaluated as false.
if condition1:
# Executes when condition1 is true
elif condition2:
# Executes when condition2 is true
else:
# else-block
Example
number = int(input(“enter the number”)) #We have typecast string to integer
if number > 0:
print("POSITIVE NUMBER")
elif number < 0:
print("NEGATIVE NUMBER")
else:
print("ZERO")
The above program to check for positive numbers can be modified using elif
statements to check for zero.
Q.36 What is the use of pylab in python? Explain the use of plot(),show(),
and title() function of pylab
PyLab is a Python package that provides us a namespace in Python
programming, which is very similar to MATLAB interface, by importing the
functions from Python Numpy and Matplotlib Module. Matplotlib Module provides
functions that help us to create visualizations of data, whereas the Numpy
Module provides efficient numerical vector calculation functions that are based on
underlying C and Fortran binary libraries.
Plot()
In Matplotlib, the plot() function is used to create various types of plots, such as
line plots, scatter plots, bar plots, and more. It allows you to visualize data by
plotting the values on a coordinate grid.
Bar Plot
import matplotlib.pyplot as plt
# Sample data
x = ['A', 'B', 'C', 'D']
y = [15, 7, 12, 9]
# Create a bar plot
plt.bar(x, y)
# Display the plot
plt.show()
OUTPUT
In this example, we have categorical data represented by the x array and their
corresponding values in the y array. We create a bar plot using plt.bar(x, y),
which displays vertical bars with heights corresponding to the values in the y
array.
These examples demonstrate just a few of the many possibilities with the plot()
function in Matplotlib. Depending on your data and visualization needs, you can
explore various plot types and customize them further using additional
parameters and functions provided by Matplotlib.
show()
In Matplotlib, the `show()` function is used to display the current figure. It opens
an interactive window and shows the plot or image that has been created using
Matplotlib functions.
Here's an example that demonstrates the usage of `show()` in Matplotlib:
import matplotlib.pyplot as plt
# Sample data
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
# Create a simple line plot
plt.plot(x, y)
# Set labels and title
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Simple Line Plot')
# Display the plot
plt.show()
OUTPUT
In this example, we first import the `matplotlib.pyplot` module as `plt`. Then, we
define some sample data with the `x` and `y` values. Next, we create a line plot
using `plt.plot(x, y)`, which connects the points defined by the `x` and `y` arrays.
We further customize the plot by setting labels for the x-axis and y-axis using
`plt.xlabel()` and `plt.ylabel()` functions. We also set a title for the plot using
`plt.title()`.
Finally, we call `plt.show()` to display the plot in an interactive window. This
function will pause the execution of the script until the window is closed by the
user.
Note that in some environments like Jupyter Notebook, you may not need to
explicitly call `show()`, as the plots are displayed automatically. However, in
standalone Python scripts or certain IDEs, the `show()` function is necessary to
view the plot.
Title()
In Matplotlib, the `title()` function is used to set the title of a plot or figure. It allows
you to provide a string that represents the title text, which will be displayed above
the plot.
Here's an example that demonstrates the usage of `title()` in Matplotlib:
EXAMPLE
import matplotlib.pyplot as plt
# Sample data
x = [1, 2, 3, 4, 5]
y = [6, 5, 6, 7, 15]
# Create a simple line plot
plt.plot(x, y)
# Set title
plt.title('Simple Line Plot')
# Display the plot
plt.show()
OUTPUT
In this example, we first import the `matplotlib.pyplot` module as `plt`. Then, we
define some sample data with the `x` and `y` values.
Next, we create a line plot using `plt.plot(x, y)`, which connects the points defined
by the `x` and `y` arrays.
To set the title of the plot, we call the `plt.title()` function and pass the desired title
text as a string. In this case, we set the title to 'Simple Line Plot'.
Finally, we call `plt.show()` to display the plot with the specified title in an
interactive window.
You can customize the appearance of the title by using additional parameters of
the `title()` function. For example, you can control the font size, font weight, color,
and other properties of the title text.
Q.37 What are mortgages? Explain various method of mortgages
ANS:- SKIP
Q.38 Explain various python functions used to connect with MYSQL
database.
Database Connection
In this section of the tutorial, we will discuss the steps to connect the python application to the
database.
There are the following steps to connect a python application to our database.
Import mysql.connector module
Create the connection object.
Create the cursor object
Execute the query
Creating the connection
To create a connection between the MySQL database and the python application, the connect()
method of mysql.connector module is used.
Pass the database details like HostName, username, and the database password in the method
call. The method returns the connection object.
The syntax to use the connect() is given below.
Connection-Object= mysql.connector.connect(host = <host-name> , user = <username> ,
passwd = <password> )
Consider the following example.
Example
import mysql.connector
#Create the connection object
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google")
#printing the connection object
print(myconn)
Output:
<mysql.connector.connection.MySQLConnection object at 0x7fb142edd780>
Here, we must notice that we can specify the database name in the connect() method if we want
to connect to a specific database.
OR
To connect and interact with a MySQL database using Python, you can utilize several libraries
and modules. Here are some commonly used ones:
1. **mysql-connector-python:** This library provides an interface for connecting to MySQL
databases using pure Python. It is an official MySQL connector and supports both Python 2 and
Python 3.
Installation: `pip install mysql-connector-python`
Example usage:
import mysql.connector
# Establish a connection
connection = mysql.connector.connect(
host='localhost',
user='your_username',
password='your_password',
database='your_database'
)
# Create a cursor object
cursor = connection.cursor()
# Execute SQL queries
cursor.execute('SELECT * FROM your_table')
# Fetch and print the results
results = cursor.fetchall()
for row in results:
print(row)
# Close the cursor and connection
cursor.close()
connection.close()
```
2. **pymysql:** This is another popular library for connecting to MySQL databases from Python.
It is a pure-Python implementation of the MySQL protocol and provides a simple and efficient
way to interact with MySQL databases.
Installation: `pip install pymysql`
Example usage:
import pymysql
# Establish a connection
connection = pymysql.connect(
host='localhost',
user='your_username',
password='your_password',
database='your_database'
)
# Create a cursor object
cursor = connection.cursor()
# Execute SQL queries
cursor.execute('SELECT * FROM your_table')
# Fetch and print the results
results = cursor.fetchall()
for row in results:
print(row)
# Close the cursor and connection
cursor.close()
connection.close()
3. **sqlite3:** Although primarily used for SQLite databases, the `sqlite3` module that comes
with Python's standard library can also be used to interact with MySQL databases. It provides a
consistent API for connecting to and querying databases.
Example usage:
import sqlite3
# Establish a connection
connection = sqlite3.connect(
host='localhost',
user='your_username',
password='your_password',
database='your_database'
)
# Create a cursor object
cursor = connection.cursor()
# Execute SQL queries
cursor.execute('SELECT * FROM your_table')
# Fetch and print the results
results = cursor.fetchall()
for row in results:
print(row)
# Close the cursor and connection
cursor.close()
connection.close()
```
These are just a few examples of the libraries and modules you can use to connect with a
MySQL database in Python. Each library has its own advantages and features, so you can
choose the one that best suits your requirements. Remember to install the necessary library
using `pip` before using it in your code.
Q.39 What do you mean by Assertion?
In Python, an assertion is a statement that is used to check if a given condition is true. It is a
way to validate assumptions or expectations about the state of the program at a specific point.
The `assert` statement is used for this purpose. It takes an expression as its argument and
evaluates it. If the expression evaluates to `True`, the program continues execution without any
interruption. However, if the expression evaluates to `False`, an `AssertionError` is raised,
indicating that the condition is not met.
The general syntax of an assertion is as follows:
assert expression, message
Here, `expression` is the condition that is being checked, and `message` is an optional string
that can be included to provide additional information about the assertion.
Here's an example to illustrate the usage of assertions:
def divide(a, b):
assert b != 0, "Cannot divide by zero!"
return a / b
result = divide(10, 5)
print(result) # Output: 2.0
result = divide(10, 0)
print(result) # Raises an AssertionError with the message "Cannot divide by zero!"
In this example, the `divide()` function takes two arguments `a` and `b` and performs division.
Before performing the division, an assertion is used to check if `b` is not equal to zero. If `b` is
zero, the assertion fails, and an `AssertionError` is raised with the specified message.
The use of assertions can help in debugging and testing code. They provide a way to catch
potential errors or incorrect assumptions early in the development process. However, it's
important to note that assertions are typically used for internal error checking during
development and are not meant to handle user input validation or as a substitute for proper
exception handling.
OR
Assertions in Python
Q.40 Explain different types of arguments in python
In Python, there are several types of arguments that can be used when defining and calling
functions. These arguments allow you to pass values to functions in different ways and provide
flexibility in function definitions. Here are the different types of arguments in Python:
1. **Positional Arguments:** These are the most common type of arguments. They are passed
to a function based on their position or order. The number and order of the arguments in the
function call must match the function definition.
Example:
```python
def add(x, y):
return x + y
result = add(3, 5)
print(result) # Output: 8
```
2. **Keyword Arguments:** In this type of argument, you can specify the values using the
parameter names during the function call. It allows you to pass arguments in any order as long
as the parameter names are provided.
Example:
```python
def greet(name, message):
print(f"{message}, {name}!")
greet(name="John", message="Hello") # Output: Hello, John!
greet(message="Hi", name="Alice") # Output: Hi, Alice!
```
3. **Default Arguments:** Default arguments are used to provide a default value to a parameter
if no argument is provided during the function call. They are defined with an initial value in the
function definition.
Example:
def greet(name, message="Hello"):
print(f"{message}, {name}!")
greet("John") # Output: Hello, John!
greet("Alice", "Hi") # Output: Hi, Alice!
4. **Variable-length Arguments:**
- **Arbitrary Arguments (`*args`):** This type of argument allows a function to accept any
number of positional arguments. The arguments are collected as a tuple within the function.
Example:
```python
def add(*args):
total = 0
for num in args:
total += num
return total
result = add(1, 2, 3, 4)
print(result) # Output: 10
```
- **Keyword Arguments (`**kwargs`):** Keyword arguments allow a function to accept any
number of keyword arguments as a dictionary. The arguments are collected as key-value pairs
within the function.
Example:
```python
def greet(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
greet(name="John", age=30) # Output: name: John age: 30
greet(city="New York", country="USA") # Output: city: New York country: USA
```
These are the main types of arguments in Python. By utilizing these argument types effectively,
you can enhance the flexibility and functionality of your functions to handle different scenarios
and requirements.
OR
Python Function Arguments (With Examples)
Q.41 describe the methods of regex, how to use regex on files explain with
example
Regular expressions (regex) in Python are implemented through the `re` module. This module
provides functions and methods to work with regular expressions, allowing you to search,
match, and manipulate text based on patterns. Here are some commonly used methods of the
`re` module:
1. **`re.search(pattern, string)`**: Searches for a pattern within a string and returns the first
occurrence as a match object. It stops searching after finding the first match.
Example:
import re
text = "Hello, World!"
match = re.search(r"World", text)
if match:
print("Pattern found.")
else:
print("Pattern not found.")
2. **`re.match(pattern, string)`**: Checks if the pattern matches at the beginning of the string
and returns a match object if found. It only checks for a match at the start of the string.
Example:
import re
text = "Hello, World!"
match = re.match(r"Hello", text)
if match:
print("Pattern found.")
else:
print("Pattern not found.")
3. **`re.findall(pattern, string)`**: Returns all non-overlapping occurrences of a pattern within a
string as a list of strings.
Example:
import re
text = "Hello, Hello, World!"
matches = re.findall(r"Hello", text)
print(matches) # Output: ['Hello', 'Hello']
4. **`re.sub(pattern, replacement, string)`**: Replaces all occurrences of a pattern in a string
with a specified replacement.
Example:
import re
text = "Hello, World!"
new_text = re.sub(r"World", "Python", text)
print(new_text) # Output: Hello, Python!
To use regex on files, you can read the file's content as a string and apply the desired regex
operations using the `re` module. Here's an example that demonstrates how to use regex on a
file in Python:
import re
# Read file contents
with open("example.txt", "r") as file:
text = file.read()
# Perform regex operations
matches = re.findall(r"\b[A-Z]+\b", text) # Find all uppercase words
# Print the matches
for match in matches:
print(match)
In this example, the file "example.txt" is opened in read mode, and its contents are stored in the
`text` variable. Then, the `re.findall()` function is used to find all uppercase words in the text
using the regex pattern `\b[A-Z]+\b`. Finally, the matches are printed one by one.
Note that regex patterns can be more complex and tailored to your specific needs. The `re`
module offers a wide range of options and methods to handle regular expressions in Python.
Q.42 Explain performing queries on data frames with example
Pandas is one of those packages that makes importing and analyzing data much easier.
Analyzing data requires a lot of filtering operations. Pandas Dataframe provides many methods
to filter a Data frame and Dataframe.query() is one of them.
Pandas DataFrame query() Method
Dataframe.query() method only works if the column name doesn’t have any empty spaces. So
before applying the method, spaces in column names are replaced with ‘_’ .
Pandas query() method Syntax
Syntax: DataFrame.query(expr, inplace=False, **kwargs)
Parameters:
expr: Expression in string form to filter data.
inplace: Make changes in the original data frame if True
kwargs: Other keyword arguments.
Return type: Filtered Data frame
Example
# importing pandas package
import pandas as pd
# making data frame from csv file
data = pd.read_csv("employees.csv")
# replacing blank spaces with '_'
data.columns = [column.replace(" ", "_") for column in data.columns]
# filtering with query method
data.query('Senior_Management == True',inplace=True)
# display
print(data)
Output
As shown in the output image, the data now only have rows where Senior Management is True.
Q.43 discuss instance and static variables with example
In Python, instance variables and static variables are used to store data within classes, but they
have different scopes and behaviors. Here's an explanation of instance variables and static
variables, along with examples:
**Instance Variables:**
Instance variables are unique to each instance (object) of a class. They are defined within the
class's methods, typically inside the `__init__()` method, and are prefixed with the `self`
keyword. Each instance of the class has its own copy of instance variables, allowing different
objects to store different values for these variables.
Example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def display(self):
print(f"Name: {self.name}, Age: {self.age}")
# Create instances of Person class
person1 = Person("John", 25)
person2 = Person("Alice", 30)
# Access and modify instance variables
print(person1.name) # Output: John
print(person2.age) # Output: 30
person1.age = 27
person2.name = "Alicia"
person1.display() # Output: Name: John, Age: 27
person2.display() # Output: Name: Alicia, Age: 30
```
In this example, the `Person` class has two instance variables: `name` and `age`. Each instance
of the class (`person1` and `person2`) has its own values for these variables. The values can be
accessed and modified using the dot notation (`object.variable`). Each instance maintains its
own separate state.
**Static Variables:**
Static variables, also known as class variables, are shared among all instances of a class. They
are defined at the class level, outside any methods, and are prefixed with the class name or the
`@classmethod` decorator. Static variables are the same for all objects of the class, and when
one object modifies the static variable, the change is reflected across all instances.
Example:
```python
class Circle:
pi = 3.14 # Static variable
def __init__(self, radius):
self.radius = radius
def calculate_area(self):
return Circle.pi * self.radius * self.radius
# Create instances of Circle class
circle1 = Circle(5)
circle2 = Circle(3)
# Access static variable
print(Circle.pi) # Output: 3.14
# Modify static variable
Circle.pi = 3.1415
# Access static variable through instances
print(circle1.pi) # Output: 3.1415
print(circle2.pi) # Output: 3.1415
# Access instance variable and calculate area
print(circle1.calculate_area()) # Output: 78.5375
print(circle2.calculate_area()) # Output: 28.2735
```
In this example, the `Circle` class has a static variable `pi`, which represents the mathematical
constant. All instances of the class share the same value of `pi`. It can be accessed using the
class name (`Circle.pi`) or through the instances (`circle1.pi`, `circle2.pi`). Modifying the static
variable reflects the change across all instances.
Static variables are useful when you have data that should be common to all objects of a class,
such as constants, configuration settings, or shared resources.
Remember that instance variables and static variables have different scopes and behaviors.
Instance variables are specific to each instance, while static variables are shared among all
instances.
OR
A variable is an entity that keeps on changing according to its behavior.
We use different types of variables throughout any programming language
There are 3 types of variables in a python programming language.
1. Instance variable
2. Local variable
3. Static variable
Instance variable
It is a variable that is associated with a particular object, and it is used to hold data coming from
the object directly.
The scope of the instance variable is inside the constructor. Also, data inside instance variable
changes from object to object. This was the tough part and yes it might seem confusing.
When you create a constructor inside the class, there are variables inside those constructors
which are used to hold data coming directly from the object of a class.
In this situation, the variables inside the constructor which holds data are called instance
variables.
In the above code on line 2, we have initialized constructor and inside that constructor, we have
two variables named ‘name’ and ‘age’ which are used to hold data coming from object s1.
These two variables ‘name’ and ‘age’ is called instance variable.
Static variable
If the value of the variable does not change from object to object and if the variable is declared
outside the method and inside the class and also the value of the variable remains the same
throughout, this type of variable is called as static variable.
You can consider this as a definition. Also, it is the easiest concept
In the above example, we have instance variables as ‘name’ and ‘age’.
We have a local variable as ‘Name’ and ‘Age’. We have defined one more variable that does not
have anything to do with the object, also defined outside a method, constructor, and inside a
class.
This variable is ‘School’, it is this variable which is called a static variable.
The reason why it is static is that it does not change from object to object and remains constant
throughout.
For your better understanding let us see all of the three types of variables that is instance
variable, local variable, and static variable all at once.
Q.44 Explain list and mutability.
In Python, a list is a built-in data structure that allows you to store a collection of
items. It is an ordered sequence of elements enclosed in square brackets (`[]`),
and each element in the list is separated by a comma. Lists in Python are
mutable, which means you can change their elements after they are created.
Here's an explanation of lists and mutability in Python:
**Lists:**
Lists are versatile and commonly used in Python to store and manipulate
collections of data. They can contain elements of different data types, such as
integers, strings, floats, or even other lists. Lists are indexed, which means you
can access individual elements by their position (index) in the list.
Example:
```python
fruits = ['apple', 'banana', 'orange']
print(fruits[0]) # Output: apple
fruits.append('grape')
print(fruits) # Output: ['apple', 'banana', 'orange', 'grape']
fruits.remove('banana')
print(fruits) # Output: ['apple', 'orange', 'grape']
fruits[1] = 'pear'
print(fruits) # Output: ['apple', 'pear', 'grape']
In this example, we define a list `fruits` containing three elements: 'apple',
'banana', and 'orange'. We can access individual elements using their index (0, 1,
2) with square brackets (`[]`). We can also modify the list by adding elements
using the `append()` method, removing elements using the `remove()` method,
and updating elements by assigning a new value to a specific index.
**Mutability:**
Mutability refers to the ability of an object to be changed after it is created. In
Python, lists are mutable, which means you can modify their elements, add or
remove elements, or change the order of elements without creating a new list.
When you modify a list, such as changing the value of an element or
appending/removing elements, the changes are made directly to the existing list
object. Other references to the same list will also reflect these changes because
they are pointing to the same memory location.
Example:
```python
numbers = [1, 2, 3, 4]
print(numbers) # Output: [1, 2, 3, 4]
numbers[2] = 10
print(numbers) # Output: [1, 2, 10, 4]
numbers.append(5)
print(numbers) # Output: [1, 2, 10, 4, 5]
In this example, we create a list `numbers` with four elements. We can modify the
list by changing the value at index 2 and appending a new element. The changes
are made directly to the existing `numbers` list object.
It's important to note that mutability in lists can have implications when working
with multiple references to the same list. Modifying a list can affect other parts of
the program that are referencing the same list, which may lead to unexpected
behavior. Therefore, it's crucial to be mindful of how mutability can impact your
code and use it appropriately based on your program's requirements.
OR
In Python, a list is a built-in data structure that allows you to store and organize a
collection of items. It is an ordered collection, meaning that the elements in a list have a
specific order and can be accessed using their indices.
Here's an example of a list in Python:
my_list = [1, 2, 3, 4, 5]
Lists can contain elements of different data types, such as integers, floats, strings, or
even other lists. You can access individual elements of a list by using their indices,
starting from 0. For example, my_list[0] would give you the first element of the list, which
is 1.
Now, let's talk about mutability. In Python, mutability refers to whether an object can be
modified after it is created. Lists in Python are mutable, which means you can change
their elements, add new elements, or remove existing elements.
Here are some common operations that demonstrate the mutability of lists:
Modifying elements:
my_list[0] = 10
This would change the value of the first element from 1 to 10.
Adding elements:
my_list.append(6)
This would add the element 6 at the end of the list.
Removing elements:
del my_list[1]
This would remove the element at index 1 from the list.
Since lists are mutable, any changes made to a list will affect the original list itself. This
can be useful when you need to update or manipulate the data stored in a list.
However, it's important to note that mutability in lists can have some implications. For
example, if you have multiple variables referencing the same list object, modifying the
list through one variable will affect all the other variables referencing the same list. This
behavior is known as aliasing.
Here's an example to illustrate aliasing and mutability:
list1 = [1, 2, 3]
list2 = list1 # Both variables reference the same list object
list1.append(4)
print(list2) # Output: [1, 2, 3, 4]
In the example above, modifying list1 also modifies list2 because they both reference
the same list object. If you want to avoid this behavior, you can create a new copy of the
list using the slice operator:
list1 = [1, 2, 3]
list2 = list1[:] # Create a new copy of the list
list1.append(4)
print(list2) # Output: [1, 2, 3]
In this case, list2 remains unaffected by the changes made to list1.
To summarize, a list in Python is a mutable data structure that allows you to store and
manipulate a collection of elements. Mutability refers to the ability to modify an object
after it is created, and lists exhibit this behavior.
Q. 45 discuss method resolution order in multiple inheritance
Method Resolution Order (MRO) in Python refers to the order in which methods are resolved or
searched for in a class hierarchy during multiple inheritance. When a class inherits from multiple
base classes, the MRO determines the sequence in which the base classes are traversed to
find and invoke the desired method.
Python uses the C3 linearization algorithm to calculate the MRO. It follows a depth-first,
left-to-right approach to determine the order of method resolution. The MRO ensures that each
method in the inheritance hierarchy is invoked exactly once and in a consistent order.
To understand the MRO in multiple inheritance, consider the following example:
```python
class A:
def greet(self):
print("Hello from A")
class B(A):
def greet(self):
print("Hello from B")
class C(A):
def greet(self):
print("Hello from C")
class D(B, C):
pass
obj = D()
obj.greet()
```
In this example, we have four cla hiiisses: `A`, `B`, `C`, and `D`. Class `A` defines a method
`greet()`. Classes `B` and `C` inherit from `A` and override the `greet()` method. Class `D`
inherits from both `B` and `C` without defining its own `greet()` method.
When we create an instance of class `D` (`obj = D()`), and invoke the `greet()` method
(`obj.greet()`), Python follows the MRO to determine the order of method resolution. In this case,
the MRO for `D` is `[D, B, C, A]`.
The MRO ensures that the method is searched for in the classes from left to right, following the
MRO order. In this example, the `greet()` method is found in class `B`, so it is invoked, and the
output will be:
Hello from B
If we change the order of inheritance for class `D` (`class D(C, B)`), the MRO would be `[D, C,
B, A]`, and the output would be:
Hello from C
This demonstrates how the MRO determines the order in which methods are resolved during
multiple inheritance. It provides a consistent and predictable way to handle method resolution
when dealing with complex class hierarchies.
OR
Method Resolution Order (MRO) is the order in which methods are searched for and
resolved in a class hierarchy that involves multiple inheritance in Python. When a class
inherits from multiple parent classes, the MRO determines the sequence in which the
methods of those parent classes are called.
Python uses the C3 linearization algorithm to calculate the MRO. The MRO follows
three main principles:
Depth-First Search: The MRO starts by traversing the inheritance graph in a depth-first
manner. It visits all the parents of a class before moving on to the next parent.
Left-to-Right Ordering: When there are multiple parents at the same level in the
inheritance hierarchy, the MRO follows a left-to-right ordering. This means that the order
of inheritance declaration matters. The methods of the leftmost parent are considered
before the methods of the parent on the right.
First Appearance Wins: If a method is present in multiple parent classes, the MRO
ensures that it is only considered from the first class where it appears. Subsequent
occurrences of the same method in other parent classes are ignored.
Let's look at an example to understand the MRO in action:
class A:
def method(self):
print("A's method")
class B(A):
def method(self):
print("B's method")
class C(A):
def method(self):
print("C's method")
class D(B, C):
pass
d = D()
d.method()
In this example, we have a class hierarchy with classes A, B, C, and D. Class D inherits
from both B and C, which in turn inherit from A. When we create an instance of class D
and call the method() function, the MRO determines the order in which the methods of
the parent classes are invoked.
The MRO for class D can be obtained using the __mro__ attribute:
print(D.__mro__)
# Output: (<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class
'__main__.A'>, <class 'object'>)
Based on the MRO, the method resolution starts with class D itself, then moves to class
B, followed by class C, class A, and finally the base object class. This means that the
method resolution order is D -> B -> C -> A -> object.
In our example, since class B is the leftmost parent, its method() is called:
B's method
If we change the order of inheritance for class D to class D(C, B), the MRO will change
accordingly, and the output will be:
C's method
Understanding the MRO is important in cases of multiple inheritance, as it helps in
determining the order in which methods are resolved and executed, ensuring that the
correct method is called based on the class hierarchy.
Q.46 discusses the steps of creating a table and inserting five records with
appropriate examples of your choice.
Here's an example of creating a table and inserting five records using SQLite in Python:
Step 1:- Connect to the database:
import sqlite3
conn = sqlite3.connect("example.db")
cursor = conn.cursor()
Step 2:- Create a table:
create_table_query = """
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
name TEXT,
email TEXT
)"""
cursor.execute(create_table_query)
In this example, we create a table called "users" with three columns: "id" (integer), "name" (text),
and "email" (text). The PRIMARY KEY constraint is used to ensure each record has a unique
identifier.
Step 3:- Insert records:
insert_query = """
INSERT INTO users (name, email) VALUES (?, ?)
"""
records = [
("John Doe", "john@example.com"),
("Jane Smith", "jane@example.com"),
("Michael Johnson", "michael@example.com"),
("Emily Davis", "emily@example.com"),
("Robert Brown", "robert@example.com")
]
cursor.executemany(insert_query, records)
In this step, we use the INSERT INTO statement to insert multiple records into the "users" table.
The ? placeholders in the query are replaced with actual values using the executemany()
method. The records variable contains a list of tuples, where each tuple represents a record to
be inserted.
Step 4:- Commit and close the connection:
conn.commit()
conn.close()
After inserting the records, it's important to commit the changes to the database and close the
connection.
That's it! You have now created a table called "users" and inserted five records into it using
SQLite in Python.
Q.47 discuss the use of super keyword with an example
In Python, the super() keyword is used to call a method from a parent class when
working with inheritance. It allows you to invoke the parent class's methods and access
its attributes within a subclass. The super() function returns a temporary object of the
superclass, which gives you access to its methods and attributes.
Here's an example that demonstrates the use of super():
class Parent:
def __init__(self):
self.parent_attribute = "I am a parent"
def parent_method(self):
print("This is a method in the parent class")
class Child(Parent):
def __init__(self):
super().__init__() # Calling the parent class's __init__() method
self.child_attribute = "I am a child"
def child_method(self):
super().parent_method() # Calling the parent class's parent_method() method
print("This is a method in the child class")
child_obj = Child()
child_obj.child_method()
In this example, we have a parent class called Parent and a child class called Child
which inherits from Parent. The child class overrides the __init__() method and defines
its own child_method(). The super().__init__() statement in the child class's __init__()
method calls the parent class's __init__() method, allowing the child class to initialize
both its own attributes and those inherited from the parent class.
Similarly, the super().parent_method() statement in the child_method() of the child class
calls the parent_method() defined in the parent class.
When we create an instance of the child class (child_obj) and call its child_method(), it
will invoke the parent class's parent_method() and print the corresponding messages:
OUTPUT
This is a method in the parent class
This is a method in the child class
The super() keyword is particularly useful when working with multiple inheritance, as it
ensures that the methods of all parent classes are called in a consistent and predictable
order according to the Method Resolution Order (MRO).
By using super(), you can effectively leverage the functionality of parent classes within
your subclasses, promoting code reuse and maintaining a clear inheritance hierarchy
Python programs
Q.48 Write a program which has class Student with the following instance
variable.(empId,empName, emp designation, Basic Salary), and having
following instance methods.calculateHRA( 15 % of Sal), calculateTA(5 % of
Sal), calculateDA( 25 % of Sal) calculateNetSal.Show proper use of class
into the main program.
class Student:
def __init__(self, empId, empName, empDesignation, basicSalary):
self.empId = empId
self.empName = empName
self.empDesignation = empDesignation
self.basicSalary = basicSalary
def calculateHRA(self):
return self.basicSalary * 0.15
def calculateTA(self):
return self.basicSalary * 0.05
def calculateDA(self):
return self.basicSalary * 0.25
def calculateNetSal(self):
return self.basicSalary + self.calculateHRA() + self.calculateTA() +
self.calculateDA()
empId = int(input("Enter employee ID: "))
empName = input("Enter employee name: ")
empDesignation = input("Enter employee designation: ")
basicSalary = float(input("Enter basic salary: "))
emp1 = Student(empId, empName, empDesignation, basicSalary)
print('Employee Name:', emp1.empName)
print('Designation:', emp1.empDesignation)
print('Basic Salary:', emp1.basicSalary)
print('HRA:', emp1.calculateHRA())
print('TA:', emp1.calculateTA())
print('DA:', emp1.calculateDA())
print('Net Salary:', emp1.calculateNetSal())
Output
Enter employee ID: 01
Enter employee name: XYZ
Enter employee designation: HR
Enter basic salary: 1000000
Employee Name: XYZ
Designation: HR
Basic Salary: 1000000.0
HRA: 150000.0
TA: 50000.0
DA: 250000.0
Net Salary: 1450000.0
Q.49 What is a regular expression? Suppose str = “Dhara Om Bhavna 123
Ekta Jay 9abc“. Write a regular expression for following requirements on
the basis of “str”:
1. Search all the words having length between 3 to 5.
2. Find all the words who start with numeric value.
3. Find all the non-alphabetic words.
"""1. Search all the word having length between 3 to 5:"""
import re
str = "Dhara Om Bhavna 123 Ekta Jay 9abc"
print(str)
pattern = r'\b\w{3,5}\b'
print("1. All the word having length between 3 to 5:")
result = re.findall(pattern, str)
print(result)
"""2. Find all the word who start with numeric value:"""
print("2. All the word who start with numeric value:")
pattern = r'\b\d\w*\b'
result = re.findall(pattern, str)
print(result)
"""3. Find all the non-alphabetic word:"""
print("3. All the non-alphabetic word:")
pattern = r'\b[^A-Za-z]+\b'
result = re.findall(pattern, str)
print(result)
Output
Dhara Om Bhavna 123 Ekta Jay 9abc
1. All the word having length between 3 to 5:
['Dhara', '123', 'Ekta', 'Jay', '9abc']
2. All the word who start with numeric value:
['123', '9abc']
3. All the non-alphabetic word:
[' ', ' ', ' 123 ', ' ', ' '
Q.50 Suppose there is a student.csv file which having data of stdid ,name,
engMark, gujMark, hinMark, and total. Find out student for following criteria
using pandas operation.
1. Create data frame from student.csv file using panda’s method.
2. Find out student who having maximum marks in engMark using data frame.
3. Find out student who having less than 35 marks in hinMark using data frame
"""1. Create data frame from student.csv file using pandas method: """
import pandas as pd
df = pd.read_csv('student.csv')
print(df)
"""
Output:
stdid name engMark gujMark hinMark total
0
1 John
80
70
60 210
1
2 Bob
70
80
90 240
2
3 Jane
90
80
70 240
3
4 Mary
60
70
80 210
This code reads the `student.csv` file and creates a pandas DataFrame.
"""
"""2. Find out student who having maximum marks in engMark using data
frame:"""
import pandas as pd
df = pd.read_csv('student.csv')
max_engMark = df.loc[df['engMark'].idxmax()]
print(max_engMark['name'], 'has the highest marks in English:',
max_engMark['engMark'])
Output:
Jane has the highest marks in English: 90
This code finds the student who has the maximum marks in English using the
`idxmax()` method and returns their name and marks.
"""
"""3. Find out student who having less than 35 marks in hinMark using data
frame:"""
import pandas as pd
df = pd.read_csv('student.csv')
less_than_35 = df.loc[df['hinMark'] < 35]
print('Students with less than 35 marks in Hindi:')
print(less_than_35)
Q.51 Write a Python program using PyLab to display strength of students in
a college for 5 years. First year strength was 3000 which increased by 5%
every year. Display graph accordingly. Use Xlabel, Ylabel, Title, Legend
accordingly.
import pylab as pl
year = [1, 2, 3, 4, 5]
strength = [3000]
for i in range(4):
strength.append(strength[i] * 1.05)
pl.plot(year, strength, '-o', label='Strength')
pl.xlabel('Year')
pl.ylabel('Number of Students')
pl.title('Student Strength in College')
pl.legend(loc='upper left')
pl.show()
Output
Q.52 Write a python program which having two function to display a record
from employee and department table as following criteria.
1. Display employee detail with department name. (first function)
2. Display employee from particular department only. (second function) Following are
structure of table. Employee(empId,empName,empSal,depId)
Department(depId,depName,depDesc)"""""
# Create the Employee and Department lists
Employee = [
{'empId': 1, 'empName': 'John', 'empSal': 50000, 'depId': 1},
{'empId': 2, 'empName': 'Mary', 'empSal': 60000, 'depId': 2},
{'empId': 3, 'empName': 'Bob', 'empSal': 70000, 'depId': 1},
{'empId': 4, 'empName': 'Alice', 'empSal': 55000, 'depId': 3},
{'empId': 5, 'empName': 'David', 'empSal': 65000, 'depId': 2},
]
Department = [
{'depId': 1, 'depName': 'IT', 'depDesc': 'Information Technology'},
{'depId': 2, 'depName': 'Sales', 'depDesc': 'Sales and Marketing'},
{'depId': 3, 'depName': 'Marketing', 'depDesc': 'Marketing and
Advertising'},
]
# Function to display employee details with department name
def display_employee_details():
# Loop through the Employee list and join with Department list using
depId
for emp in Employee:
dep = next((d for d in Department if d['depId'] == emp['depId']), None)
if dep:
print(emp['empId'], emp['empName'], emp['empSal'],
dep['depName'])
Output
1 John 50000 IT
2 Mary 60000 Sales
3 Bob 70000 IT
4 Alice 55000 Marketing
5 David 65000 Sales
2 Mary 60000
5 David 65000
Q.53 Write a python program which show to insert and delete records in
Product table with following fields.
(prodId,prodName,qty,rate,brandName)"""
# Define an empty list to store the products
products = []
# Function to insert a record into the Product table
def insert_product(prodId, prodName, qty, rate, brandName):
product = {'prodId': prodId, 'prodName': prodName, 'qty': qty, 'rate': rate,
'brandName': brandName}
products.append(product)
# Function to delete a record from the Product table
def delete_product(prodId):
for product in products:
if product['prodId'] == prodId:
products.remove(product)
# Call the functions to test them
insert_product(1, 'Product 1', 10, 100.0, 'Brand 1')
insert_product(2, 'Product 2', 20, 200.0, 'Brand 2')
delete_product(1)
# Print the contents of the Product table
for product in products:
print(product)
Output
{'prodId': 2, 'prodName': 'Product 2', 'qty': 20, 'rate': 200.0, 'brandName':
'Brand 2'}
Q.54 1 . Write a program to retrieve all rows from Student table and display
the Column values in tabular form. 2. Write program to create emp_table in
MySQL database."""
import mysql.connector
# Connect to the database
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
# Create a cursor object
mycursor = mydb.cursor()
# Retrieve all rows from the Student table
mycursor.execute("SELECT * FROM Student")
rows = mycursor.fetchall()
# Print the column names
print("ID\tName\t\tAge\tGender")
print("-" * 40)
# Print the rows in tabular form
for row in rows:
print(f"{row[0]}\t{row[1]}\t\t{row[2]}\t{row[3]}")
2. Write program to create emp_table in MySQL database.
import mysql.connector
# Establish a connection to the MySQL database
mydb = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="your_database"
)
# Create a cursor object to execute SQL queries
cursor = mydb.cursor()
# Define the CREATE TABLE query
create_table_query = """
CREATE TABLE emp_table (
emp_id INT PRIMARY KEY,
emp_name VARCHAR(50),
emp_salary FLOAT,
emp_dept VARCHAR(50)
)
"""
# Execute the CREATE TABLE query
cursor.execute(create_table_query)
# Commit the changes to the database
mydb.commit()
# Close the cursor and the database connection
cursor.close()
mydb.close()
Q.55 Write a python program which show to insert and delete records in
employee table with following fields. (emp_id , emp_name , emp_mnumber
, emp_project )
import mysql.connector
# Connect to the MySQL server
mydb = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="your_database"
)
# Create a cursor object to interact with the database
cursor = mydb.cursor()
# Function to insert a record into the employee table
def insert_employee(emp_id, emp_name, emp_mnumber, emp_project):
query = "INSERT INTO employee (emp_id, emp_name, emp_mnumber, emp_project)
VALUES (%s, %s, %s, %s)"
values = (emp_id, emp_name, emp_mnumber, emp_project)
cursor.execute(query, values)
mydb.commit()
print("Record inserted successfully.")
# Function to delete a record from the employee table
def delete_employee(emp_id):
query = "DELETE FROM employee WHERE emp_id = %s"
value = (emp_id,)
cursor.execute(query, value)
mydb.commit()
print("Record deleted successfully.")
# Example usage
# Inserting a record
insert_employee(1, "John Doe", "1234567890", "Project X")
# Deleting a record
delete_employee(1)
# Close the cursor and the database connection
cursor.close()
mydb.close()
Q.56 Write a program using GUI to retrieve a row from a MySQL database
table
import mysql.connector
from tkinter import *
# Connect to the database
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
# Create a cursor object
mycursor = mydb.cursor()
# Create a GUI window
root = Tk()
# Set the title of the window
root.title("Retrieve a Row")
# Set the size of the window
root.geometry("400x200")
# Create a label for the ID input
id_label = Label(root, text="Enter ID:")
id_label.pack()
# Create an entry box for the ID input
id_entry = Entry(root)
id_entry.pack()
# Create a function to retrieve the row
def retrieve_row():
# Get the ID from the entry box
id = id_entry.get()
# Execute a SELECT statement to retrieve the row with the given ID
mycursor.execute("SELECT * FROM mytable WHERE id = %s", (id,))
row = mycursor.fetchone()
# Create a label for each column value
id_label = Label(root, text="ID: " + str(row[0]))
id_label.pack()
name_label = Label(root, text="Name: " + row[1])
name_label.pack()
age_label = Label(root, text="Age: " + str(row[2]))
age_label.pack()
gender_label = Label(root, text="Gender: " + row[3])
gender_label.pack()
# Create a button to retrieve the row
retrieve_button = Button(root, text="Retrieve", command=retrieve_row)
retrieve_button.pack()
# Start the main loop
root.mainloop()
Q.57 Write a program to find factorial with Iterative and Recursive methods
# Iterative method
def factorial_iterative(n):
result = 1
for i in range(1, n+1):
result *= i
return result
# Recursive method
def factorial_recursive(n):
if n == 1:
return 1
else:
return n * factorial_recursive(n-1)
# Get input from user
n = int(input("Enter a number: "))
# Call functions and print results
print("Factorial using iterative method:", factorial_iterative(n))
print("Factorial using recursive method:", factorial_recursive(n))
Output
Enter a number: 5
Factorial using iterative method: 120
Factorial using recursive method: 120
Q.58 Write syntax for function in python. Write a code to find maximum of
two given numbers. Explain the use and creation, parameter passing in
function. in python
"""Here's the syntax for creating a function in Python:"""
def function_name(parameter1, parameter2, ...):
# code block
return value
def find_maximum(num1, num2):
if num1 > num2:
return num1
else:
return num2
"""In this function, we have two parameters `num1` and `num2` that represent the
two numbers we want to compare. We use an `if` statement to check if `num1` is
greater than `num2`. If it is, we return `num1`. If it's not, we return `num2`.
To call this function, we simply pass in two numbers as arguments:"""
max_num = find_maximum(5, 10)
print(max_num)
"""This will output `10`, since `10` is the larger of the two numbers.Functions are
useful because they allow us to write reusable code. We can define a function
once and then call it multiple times with different arguments. Functions can also
help make our code more organized and easier to read.
In Python, we can pass parameters to a function in a few different ways. We can
pass them by position, which means the order of the arguments matters. We can
also pass them by name, which means we specify which argument corresponds
to each parameter. Additionally, we can provide default values for parameters,
which means they can be omitted when calling the function."""
Q.59 Write a program to find Largest number out of three numbers using
function.
def find_largest(num1, num2, num3):
if num1 > num2 and num1 > num3:
return num1
elif num2 > num1 and num2 > num3:
return num2
else:
return num3
# Get input from user
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
num3 = int(input("Enter third number: "))
# Call function and print result
largest_num = find_largest(num1, num2, num3)
print("The largest number is:", largest_num)
Q.60 1.Write a program to implement Factorial series up to user entered number by
using recursive Function.
ANS - NO.09
2)Write python program to retrieve information from a HTML File using a regular expression.
import re
# Open the HTML file and read its contents
with open('example.html', 'r') as f:
html = f.read()
# Define a regular expression pattern to match the information you want to
extract
pattern = r'<h1>(.*?)</h1>'
# Use the re.findall() function to extract all matches of the pattern from the HTML
matches = re.findall(pattern, html)
# Print out the matches
print(matches)
Q.61 Write a program to retrieve all rows from Student table and display the
Column values and how to handling the missing values.
# Define the Student list
students = [
{"id": 1, "name": "Alice", "age": 20},
{"id": 2, "name": "Bob", "age": None},
{"id": 3, "name": None, "age": 22},
{"id": 4, "name": "Dave", "age": 19},
{"id": 5, "name": "Eve", "age": 21}
]
# Loop through the students and print out the column values
for student in students:
# Check if the name is missing
if student["name"] is None:
name = "Unknown"
else:
name = student["name"]
# Check if the age is missing
if student["age"] is None:
age = "Unknown"
else:
age = student["age"]
# Print out the row with the missing values handled
print("ID:", student["id"], "Name:", name, "Age:", age)
Output
ID: 1 Name: Alice Age: 20
ID: 2 Name: Bob Age: Unknown
ID: 3 Name: Unknown Age: 22
ID: 4 Name: Dave Age: 19
ID: 5 Name: Eve Age: 21
Q.62 Write following programs for regular expressions.
1. To search for string starting with m and having total three characters
using the search(), findall() and map() methods.
import re
strings = ['man', 'cat', 'mat', 'dog', 'map', 'mop']
# Use search() method
for string in strings:
if re.search('^m\w{2}$', string):
print(f"search() method: Found string: {string}")
# Use findall() method
matches = re.findall('^m\w{2}$', ' '.join(strings))
if matches:
print(f"findall() method: Found strings: {matches}")
# Use map() method
matches = list(filter(None, map(lambda string: re.search('^m\w{2}$', string),
strings)))
if matches:
print(f"map() method: Found strings: {[match.group() for match in matches]}")
OUTPUT
search() method: Found string: man
search() method: Found string: mat
search() method: Found string: map
search() method: Found string: mop
map() method: Found strings: ['man', 'mat', 'map', 'mop']
2. To split a string into pieces where one or more non alpha numeric characters are found.
import re
string = "Hello, world! How are you today?"
pieces = re.split(r'\W+', string)
print(pieces)
Q.63 Write a python program to pass a function as parameter to another
function.
def add(x, y):
return x + y
def multiply(x, y):
return x * y
def apply_operation(operation, x, y):
return operation(x, y)
result1 = apply_operation(add, 2, 3)
result2 = apply_operation(multiply, 2, 3)
print(f"Result of add operation: {result1}")
print(f"Result of multiply operation: {result2}")
Q.64 Discuss all key points for retrieving information from a HTML file.
Write a program to explain the same.""""""To retrieve information from an
HTML file, you can use a Python library such as Beautiful Soup or lxml.
Here are the key points for retrieving information from an HTML file:
1. Parse the HTML file: Use a parser to convert the HTML file into a parse tree, which is
a hierarchical structure that represents the HTML document.
2. Locate the information: Use the parse tree to locate the information you want to
retrieve. You can do this by searching for specific tags, attributes, or text.
3. Extract the information: Once you have located the information, extract it from the
HTML file. This can involve getting the text of a tag, getting the value of an attribute, or
getting the contents of a specific tag.Here is an example program that demonstrates
how to retrieve information from an HTML file using Beautiful Soup:
from bs4 import BeautifulSoup
# Load the HTML file
with open('example.html') as f:
html = f.read()
# Parse the HTML file
soup = BeautifulSoup(html, 'html.parser')
# Locate the information
title = soup.title.text
paragraphs = soup.find_all('p')
links = soup.find_all('a')
# Extract the information
print(f'Title: {title}')
print('Paragraphs:')
for p in paragraphs:
print(p.text)
print('Links:')
for link in links:
print(link.get('href'))
**THE END**
Download