Unit 3 & 4
Unit 3 & 4
•r - Opens the file for reading only. This is the default mode.
•w - Opens the file for writing only. If the file exists, it will be overwritten. If the
file does not exist, it will be created.
•a - Opens the file for appending. The file pointer will be placed at the end of
the file.
• r+ - Opens the file for reading and writing.
• w+ - Opens the file for writing and reading. If the file exists, it will be
overwritten. If the file does not exist, it will be created.
• a+ - Opens the file for appending and reading. The file pointer will be placed at
the end of the file.
• rb - Opens the file in binary mode for reading only.
• wb - Opens the file in binary mode for writing only. If the file exists, it will be
overwritten. If the file does not exist, it will be created.
• ab - Opens the file in binary mode for appending. The file pointer will be
placed at the end of the file.
• rb+ - Opens the file in binary mode for reading and writing.
• wb+ - Opens the file in binary mode for writing and reading. If the file exists, it
will be overwritten. If the file does not exist, it will be created.
• ab+ - Opens the file in binary mode for appending and reading. The file pointer
will be placed at the end of the file.
For example, the following code opens the file myfile.txt in read mode:
Python
with open("myfile.txt", "r") as file:
content = file.read()
print(content)
2. With program example explain how ‘with’ statement is used to open and close files
The with statement is a context manager that allows us to open and close files
automatically. The syntax for the with statement is:
Python
with open(filename, mode) as file:
# Do something with the file
The filename argument is the name of the file to open. The mode argument is the file
opening mode.
The with statement will automatically close the file when the indented block of code
is finished executing. This is useful because it helps to prevent us from forgetting to
close the file, which can lead to file corruption.
For example, the following code opens the file myfile.txt in read mode and then
prints the contents of the file:
Python
with open("myfile.txt", "r") as file:
print(file.read())
3. With code example explain any two methods to read data from the file.
There are two main methods for reading data from a file in Python:
• The read() method reads the entire contents of the file and returns it as a
string.
• The readline() method reads one line from the file and returns it as a string.
For example, the following code reads the entire contents of the file myfile.txt and
prints it to the console:
Python
with open("myfile.txt", "r") as file:
data = file.read()
print(data)
The following code reads one line from the file myfile.txt and prints it to the
console:
Python
with open("myfile.txt", "r") as file:
line = file.readline()
print(line)
4. With Code example explain any two methods to write data to the file.
There are two main methods for writing data to a file in Python:
For example, the following code writes the string "Hello, world!" to the file
myfile.txt:
Python
with open("myfile.txt", "w") as file:
file.write("Hello, world!")
Python
with open("myfile.txt", "w") as file:
file.writelines(["Hello
5. Write Python Program to Count the Occurrences of Each Word and Also Count
the Number of Words in a text File.
Python
import re
def word_count(file_name):
with open(file_name, "r") as file:
data = file.read()
return counts
def main():
file_name = "myfile.txt"
counts = word_count(file_name)
if __name__ == "__main__":
main()
This program first opens the file myfile.txt in read mode and reads the contents of
the file into a variable called data. Then, it uses the re.split() method to split the
data into a list of words. Next, it creates a dictionary called counts to store the word
counts. For each word in the list of words, it checks if the word is already in the
dictionary. If it is, it increments the count of the word. If it is not, it adds the word to
the dictionary with a count of 1. Finally, it prints the number of words in the file and
the word counts.
To run the program, you can save it as a .py file and then run it from the command
line:
Code snippet
python word_count.py
6. Explain declaring a class, defining an object and constructor with syntax and
example.
In Python, a class is declared using the class keyword. The name of the class
should be followed by a colon (:) and a block of code. The block of code can contain
attributes (variables) and methods (functions).
Python
class Animal:
pass
animal = Animal()
For example, the following code defines a __init__() method for the Animal class:
Python
class Animal:
def __init__(self, name):
self.name = name
animal = Animal("Dog")
print(animal.name)
Code snippet
Dog
Inheritance is a way to reuse code and create new classes from existing classes. In
Python, inheritance is implemented using the inherits keyword.
To inherit from a class, we use the inherits keyword followed by the name of the
class we want to inherit from. For example, the following code defines a Dog class
that inherits from the Animal class:
Python
class Animal:
def __init__(self, name):
self.name = name
class Dog(Animal):
pass
dog = Dog("Dog")
print(dog.name)
This code will print the same output as the previous code, because the Dog class
inherits the __init__() method from the Animal class.
For example, the following code defines a Dog class that inherits from the Animal
class and overrides the __init__() method:
Python
class Animal:
def __init__(self, name):
self.name = name
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name)
self.breed = breed
print(dog.name)
print(dog.breed)
Code snippet
Dog
Golden Retriever
As you can see, the Dog class overrides the __init__() method from the Animal
class and provides a new implementation that takes two arguments: the name of the
dog and the breed of the dog.
9. Explain multi-level inheritance with example.
Python
class Object:
pass
class Animal(Object):
pass
class Dog(Animal):
pass
dog = Dog()
print(dog.__class__)
Code snippet
<class '__main__.Dog'>
As you can see, the dog object is an instance of the Dog class, which is an instance
of the Animal class, which is an instance of the Object class.
Python
class Vehicle:
pass
class Engine:
pass
car = Car()
print(car.__class__)
Python
class Vehicle:
pass
class Engine:
pass
The Car class inherits the methods and attributes from both the Vehicle class and
the Engine class.
Method overloading is when a class has multiple methods with the same name but
different parameters. For example, the following code defines a Calculator class
that has two methods called add():
Python
class Calculator:
def add(self, a, b):
return a + b
The first add() method takes two parameters, while the second add() method takes
three parameters. The method that is called will be the one that matches the number
and types of parameters that are passed to it.
Method overriding is when a subclass defines a method with the same name as a
method in its superclass. The subclass method will override the superclass method if
the method is called in an object of the subclass. For example, the following code
defines a Dog class that inherits from the Animal class:
Python
class Animal:
def speak(self):
print("I am an animal!")
class Dog(Animal):
def speak(self):
print("Woof!")
The Dog class overrides the speak() method from the Animal class. If a Dog object
calls the speak() method, the Woof! message will be printed to the console.
13. Explain the steps involved in creating a GUI application in Python with a suitable
example.
To create a GUI application in Python, you will need to use the Tkinter library. The
Tkinter library provides a set of classes and functions that you can use to create
graphical user interfaces.
Python
import tkinter as tk
def button_clicked():
print("The button was clicked!")
root = tk.Tk()
root.mainloop()
This code will create a Tk object and a Button widget. The Button widget will be
displayed on the Tk object. When the Button widget is clicked, the button_clicked()
function will be called. The button_clicked() function will print a message to the
console.
To run the application, you can save the code as a .py file and then run it from the
command line:
Code snippet
python my_app.py
This will open a window with the button in it. You can click the button to see the
message printed to the console.
14. How to create a button widget and bind it to the event handler? Explain with
example.
To create a button widget in Python, you can use the Tkinter library. The Tkinter
library provides a Button class that you can use to create buttons.
To bind an event handler to a button widget, you can use the bind() method. The
bind() method takes two arguments: the event type and the event handler. The
event type is the type of event that you want to bind the handler to. The event
handler is the function that you want to call when the event occurs.
Here is an example of how to create a button widget and bind it to an event handler:
Python
import tkinter as tk
def button_clicked():
print("The button was clicked!")
root = tk.Tk()
root.mainloop()
This code will create a Tk object and a Button widget. The Button widget will be
displayed on the Tk object. When the Button widget is clicked, the button_clicked()
function will be called. The button_clicked() function will print a message to the
console.
The bind() method in the code above binds the <Button-1> event to the
button_clicked() function. The <Button-1> event is the event that occurs when the
user clicks the left mouse button on the button.
Layout managers are used to arrange widgets in a frame. There are several different
layout managers available in Tkinter, each with its own advantages and
disadvantages.
• pack(): The pack() layout manager arranges widgets in a grid. The widgets
are arranged in rows and columns, and the size of each widget is determined
by its contents.
• place(): The place() layout manager arranges widgets in absolute positions.
The position of each widget is specified by its x and y coordinates.
• grid(): The grid() layout manager is similar to the pack() layout manager, but it
gives you more control over the size and position of each widget.
• flow(): The flow() layout manager arranges widgets in a single row or column,
depending on the width or height of the frame. The widgets are arranged from
left to right or top to bottom, depending on the orientation of the frame.
The best layout manager to use depends on the specific needs of your application. If
you need to arrange widgets in a grid, the pack() layout manager is a good choice. If
you need to arrange widgets in absolute positions, the place() layout manager is a
good choice. If you need to have more control over the size and position of each
widget, the grid() layout manager is a good choice. And if you need to arrange
widgets in a single row or column, the flow() layout manager is a good choice.
Here is an example of how to use the pack() layout manager to arrange widgets in a
frame:
Python
import tkinter as tk
root = tk.Tk()
frame = tk.Frame(root)
frame.pack()
root.mainloop()
This code will create a Tk object, a Frame widget, and three Button widgets. The
Frame widget will be placed in the Tk object, and the Button widgets will be placed in
the Frame widget. The Button widgets will be arranged in a grid, with one button per
row.
To run the application, you can save the code as a .py file and then run it from the
command line:
Code snippet
python my_app.py
This will open a window with the frame and the buttons in it.
16.Explain the process of creating a Listbox widget with a suitable example. Also,
explain different values associated with selectmode option.
A listbox widget is a Tkinter widget that displays a list of items. The items in the list
can be selected by the user.
To create a listbox widget, you can use the Listbox() class. The Listbox() class
takes several arguments, but the most important ones are:
Python
import tkinter as tk
root = tk.Tk()
root.mainloop()
This code will create a Tk object, a Listbox widget, and three items in the listbox
widget. The listbox widget will be displayed on the Tk object. The items in the listbox
widget can be selected by the user.
The selectmode option of the Listbox() class specifies how the items in the listbox
widget can be selected. The different values that can be used for the selectmode
option are:
17.Write a note on
i) Text Widget
A text widget is a Tkinter widget that displays text. The text widget can be used to
display static text, or it can be used to allow the user to enter text.
To create a text widget, you can use the Text() class. The Text() class takes
several arguments, but the most important ones are:
Python
import tkinter as tk
root = tk.Tk()
root.mainloop()
This code will create a Tk object, a Text widget, and some text in the text widget. The
text widget will be displayed on the Tk object. The text in the text widget can be
edited by the user.
An entry widget is a Tkinter widget that allows the user to enter text. The entry
widget can be used to collect input from the user.
To create an entry widget, you can use the Entry() class. The Entry() class takes
several arguments, but the most important ones are:
Python
import tkinter as tk
root = tk.Tk()
root.mainloop()
This code will create a Tk object, an Entry widget, and some text in the entry widget.
The entry widget will be displayed on the Tk object. The text in the entry widget can
be edited by the user.
UNIT-4
4\6 MARKS
The SQLite module provides several methods that are required to use SQLite
databases. These methods include:
• Creating a table: This operation creates a new table in the database. For
example, the following code creates a table called students:
Python
import sqlite3
conn = sqlite3.connect("my_database.db")
c = conn.cursor()
conn.commit()
• Inserting data into a table: This operation inserts data into a table. For
example, the following code inserts two rows into the students table:
Python
import sqlite3
conn = sqlite3.connect("my_database.db")
c = conn.cursor()
c.execute("INSERT INTO students (name, age) VALUES ('Alice', 20)")
conn.commit()
• Querying a table: This operation retrieves data from a table. For example, the
following code retrieves all the rows from the students table:
Python
import sqlite3
conn = sqlite3.connect("my_database.db")
c = conn.cursor()
rows = c.fetchall()
• Updating data in a table: This operation updates data in a table. For example,
the following code updates the age of the student named "Alice" to 22:
Python
import sqlite3
conn = sqlite3.connect("my_database.db")
c = conn.cursor()
conn.commit()
• Deleting data from a table: This operation deletes data from a table. For
example, the following code deletes the row where the name is "Bob":
Python
import sqlite3
conn = sqlite3.connect("my_database.db")
c = conn.cursor()
conn.commit()
Python
import sqlite3
conn = sqlite3.connect("my_database.db")
c = conn.cursor()
# Create a table
c.execute("CREATE TABLE students (name text, age integer)")
conn.commit()
rows = c.fetchall()
conn.commit()
conn.commit()
This program will create a table called students, insert two rows into the table, query
the table, update the data in the table, and delete data from the table.
The NumPy array has several attributes that can be used to get information about
the array. These attributes include:
Python
import numpy as np
print(arr.ndim) # Prints 1
print(arr.size) # Prints 5
print(arr.itemsize) # Prints 4
There are several NumPy array creation functions available. Here are four of the
most commonly used functions:
Python
import numpy as np
These are just a few of the many NumPy array creation functions available. For more
information, you can refer to the NumPy documentation
6. Write a note on Indexing, slicing, and iterating operations on NumPy array.
NumPy arrays can be indexed, sliced, and iterated over in a similar way to Python
lists.
Indexing
For example, the following code will access the first element of the NumPy array arr:
Python
import numpy as np
print(arr[0])
Slicing
For example, the following code will access the sub-array of arr starting from the
second element to the fourth element:
Python
import numpy as np
print(arr[1:4])
Iterating
Iterating is the process of accessing each element in a NumPy array one at a time.
To iterate over a NumPy array, you can use the for loop.
For example, the following code will iterate over the NumPy array arr and print each
element:
Python
import numpy as np
for i in arr:
print(i)
• Addition: +
• Subtraction: -
• Multiplication: *
• Division: /
• Modulus: %
• Exponentiation: **
For example, the following code will add the two NumPy arrays arr1 and arr2:
Python
import numpy as np
print(arr1 + arr2)
Code snippet
[7 9 11 13 15]
Sure, here are the answers to your questions:
8. With code examples explain creating pandas series using Scalar data and
Dictionary.
A Pandas Series is a one-dimensional labeled array that can hold any data type. It is
similar to a NumPy array, but it has an index that associates each element with a
label.
To create a Pandas Series from scalar data, you can use the Series() constructor.
The Series() constructor takes two arguments: the data and the index. The data
can be any Python object, and the index can be any sequence of objects.
For example, the following code will create a Pandas Series from the scalar data 1:
Python
import numpy as np
import pandas as pd
data = 1
print(series)
Code snippet
0 1
dtype: int64
To create a Pandas Series from a dictionary, you can use the Series() constructor.
The Series() constructor takes two arguments: the dictionary and the index. The
dictionary can be any Python dictionary, and the index can be any sequence of
objects.
For example, the following code will create a Pandas Series from the dictionary {1:
"one", 2: "two", 3: "three"}:
Python
import numpy as np
import pandas as pd
print(series)
Code snippet
0 one
1 two
2 three
dtype: object
9. Explain any four string processing methods supported by Pandas Library with
example.
lower_string = string.lower()
print(len(lower_string))
This code will print the number 11, which is the length of the lowercase string "hello
world".
• str.strip(): This method removes whitespace from the beginning and end
of a string.
• str.replace(): This method replaces a substring in a string with another
substring.
• str.find(): This method returns the index of the first occurrence of a
substring in a string.
• str.rfind(): This method returns the index of the last occurrence of a
substring in a string.
10.Explain with example any two methods of creating DataFrame.
A Pandas DataFrame is a two-dimensional labeled array that can hold any data type.
It is similar to a NumPy array, but it has an index that associates each row with a
label and a column that associates each column with a label.
There are several ways to create a Pandas DataFrame. Here are two examples:
• From a list of lists: This method creates a DataFrame from a list of lists. The
lists must have the same length, and each list must contain the same number
of elements.
• From a dictionary of lists: This method creates a DataFrame from a dictionary
of lists. The keys of the dictionary are the column names, and the values of
the dictionary are the lists of data for each column.
For example, the following code will create a DataFrame from a list of lists:
Python
import numpy as np
import pandas as pd
print(df)
Sure, here are the answers to your questions:
print(selected_df)
print(filtered_df)
Code snippet
a b c
2 7 8
• Adding columns: This operation adds a new column to a DataFrame. For
example, the following code will add a column named "d" to the DataFrame
df and set the values in the column to the square of the values in the "a"
column:
Python
df["d"] = df["a"] ** 2
print(df)
Code snippet
a b c d
0 1 2 1 1
1 4 5 9 16
2 7 8 49 64
• Summarizing data: This operation summarizes the data in a DataFrame. For
example, the following code will calculate the mean, standard deviation,
minimum, and maximum values of the values in the "a" column of the
DataFrame df:
Python
summary_df = df["a"].describe()
print(summary_df)
print(merged_df)
Code snippet
a b c
0 1 4 7
1 4 5 8
2 5 6 9
3. Create a bar object using the bar() function. The bar() function takes two
arguments: the data and the labels. The data is the list of values that you want
to plot, and the labels are the list of labels that you want to use for the bars.
4. Add the bar object to the figure object.
Python
import matplotlib.pyplot as plt
# Create a histogram
plt.hist(data)
14. Write a Python program to display a pie chart showing percentage of employees
in each department. Assume there are 4 departments namely Sales, Production, HR
and Finance.
Python
import matplotlib.pyplot as plt
This code will create a pie chart showing the percentage of employees in each
department. The title of the figure is "Employees by Department". The pie chart will
be shown in a pop-up window.
15. Write a Python Program to create a Line Graph showing number of students of a
college in various Years. Consider 8 years data.
Python
import matplotlib.pyplot as plt
# Create a list of years
years = [2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017]
This code will create a line graph showing the number of students in a college in
various years. The title of the figure is "Number of Students by Year". The x-axis
label is "Year". The y-axis label is "Number of Students". The line graph will be
shown in a pop-up window.