Unit 3 Python
Unit 3 Python
Text files: These files store data in the form of characters. They are the most common type of file in
Python, and can be used to store any kind of text data, such as code, documentation, or even plain
text. Example: my_file.txt(html,css,py)
Binary files: These files store data in the form of bytes. They are often used to store images, audio, or
video files. Example: my_image.png(pdf,jpg)
“r” Opens the file in read only mode and this is the default mode.
“x” Creates a new file. If the file already exists, the operation fails
“a” Opens the file for appending data at the end of the file automatically
Statement_1
Statement_N
4.List any two file object attributes and mention its purpose.
file_handler.closed :It returns a Boolean True if the file is closed or False otherwise.
file_handler.mode: It returns the access mode with which the file was opened.
seek() method is used to move the file pointer to a specific position in the file,
tell() method is used to get the current position of the file pointer
statement(s)
7. What is self-variable ?
’self’ is a default variable that contains the memory address of the instance of the current class. So,
we ca n use ’self’ to refer to all the instance variables and instance methods. the self variable:-- is a
special variable that refers to the current instance of the class. It is used to access the instance’s
attributes and methods. The self variable is always the first argument to any method in a class
To return an object from a method in Python, you can use the return statement. The return
statement take s an object as its argument, and the object is returned to the caller of the method.
return a+b
sum(5,15) #20
Instance variables or methods, which can be accessed within the same class and can’t beseen
outside, are called private instance variables or private methods..
However, there are naming conventions that can be used to indicate that an attribute or method
should be treated as private. By convention, a single leading underscore _ is used to indicate that an
attribute or method is intended to be private.
class MyClass:
def __init__(self):
def _private_method(self):
def public_method(self):
obj = MyClass()
obj.public_method()
#42
Multipath inheritance when class is derived from two or more classes which derived from the same
base class then such type of inheritance is called.
11.What is purpose of super() method in inheritance ?
The super() method in Python is used to access methods and properties of a parent class from within
a child class. This helps reduce repetition in your code. super() does not accept any arguments.
self.name = name
class Student(Person):
super().__init__(name)
self.school = school
<statement-1>
.
<statement-N>
The process of making an operator to exhibit different behaviors in different instances is known as
operat or overloading. Operator overloading is a specific case of polymorphism, where an operator
can have different meaning when used with operands of different types.
Eg:
class example:
self.X = X
the root window is the top-level window in a Tkinter application. It is the window that
contains all of the other windows in the application. The root window is created by calling
the Tk() method. The root window is the top level window that provides rectangular space
on the screen where we can display text, colors, images, components, etc.
root = tk.Tk()
root.title("My Application")
root.geometry("500x300")
root.mainloop()
A canvas is a rectangular area which can be used for drawing pictures like lines, circles,
polygons, arcs, etc.
Features Can draw shapes, lines, text, and images Cannot draw shapes, lines, text, or images
import tkinter as tk
root = tk.Tk()
text_widget = scrolledtext.ScrolledText(root)
scrollbar = tk.Scrollbar(root)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
text_widget.config(yscrollcommand=scrollbar.set)
scrollbar.config(command=text_widget.yview)
text_widget.pack(fill=tk.BOTH, expand=True)
root.mainloop()
Purpose Displaying text or images Displaying multiple lines of text that can be edited by the user
Features Can only display a single line of text Can display multiple lines of text, and can be edited by the user
Entry widget is useful to create a rectangular box that can be used to enter or display one
line of text. For example, we can display names, passwords or credit card numbers using
Entry widgets. An Entry widget can be created as an object of Entry class as:
A Spinbox widget allows the user to select values from a given set of values.The values may be a
range of numbers or a fixed set of strings.The spin box appears as a long rectangle attached with
arrowheads pointing towards up and down.
4m
w - Open a file for writing. If the file does not exist, it will be created. If the file does exist, its
contents will be overwritten.
f.close()
a - Open a file for appending. If the file does not exist, it will be created. If the file does exist,
new data will be appended to the end of the file.
f.close()
r+ - Open a file for reading and writing. This mode allows you to read and write to the file at
the same time.
f.read()
f.close()
w+ - Open a file for writing and reading. If the file does not exist, it will be created. If the file
does exist, its contents will be overwritten. This mode allows you to read and write to the file
at the same time.
f.read()
f.close()
x - Open a file for exclusive creation. If the file already exists, the operation will fail.
Eg: try:
f = open("myfile.txt", "x")
except FileExistsError:
2.With program example explain how ‘with’ statement is used to open and close files
The with statement is a control flow statement that allows you to open and close a file in a single
statement. The with statement ensures that the file is closed properly, even if an exception is raised
content = f.read()
print(content)
open("myfile.txt", "r") - This is the expression that opens the file. The open() function takes
two arguments: the filename and the mode. The mode can be r, w, a, r+, w+, or a+.
f.read() - This is the statement that reads the contents of the file. The read() method returns
the contents of the file as a string.
print(content) - This is the statement that prints the contents of the file
3. With code example explain any two methods to read data from the file
The read() method reads the entire contents of a file and returns it as a string.
Eg:
def read_file(filename):
content = f.read()
return content
content = read_file("myfile.txt")
print(content)
The readlines() method reads the contents of a file line by line and returns a list of strings.
def read_file(filename):
lines = f.readlines()
return lines
lines = read_file("myfile.txt")
print(line)
4. With Code example explain any two methods to write data to the file.
The write() method is used to write data to a file. It takes a string as an argument and writes it to the
file.
f.write(content)
The writelines() :method is used to write multiple lines of data to a file. It takes a list of strings as an
argument and writes each string as a separate line to the file.
f.writelines(lines)
write_file("myfile.txt", lines)
5. Write Python Program to Count the Occurrences of Each Word and Also Count the Number of
Words in a text File.
wordcount = {}
wordcount[word] = 1
else:
wordcount[word] += 1
print(key, value)
hi 2
hello 1
star 1
6. Explain declaring a class, defining an object and constructor with syntax and example.
e. In Python, a class is a blueprint for creating objects. It defines the data and behavior that all
objects of that type share. To declare a class, you use the class keyword. The syntax for declaring a
class is as follows:
class ClassName:
<statement-1>
<statement-N>
To define an object of a class, you simply create an instance of the class by calling the class name
followed by parentheses
The constructor is a special method that is called when an object is created. It is used to initialize the
object’s data.
statement(s) eg:
class Person:
self.name = name
class Student(Person):
super().__init__(name)
self.school = school
Inheritance enables new classes to receive or inherit variables and methods of existing classes and
helps to reuse code.
Inheritance is a powerful feature of object-oriented programming (OOP) that allows one class to
inherit the properties and methods of another class
Implement:
class BaseClass:
class DerivedClass(BaseClass):
the above syntax, the DerivedClass is derived from the BaseClass. The DerivedClass inherits all the
attributes and methods of the BaseClass and can also define its own additional attributes and
methods.eg:
class Animal:
def speak(self):
print("Animal Speaking")
class Dog(Animal):
def bark(self):
print("dog barking")
d = Dog()
To override a superclass constructor, you need to define a __init__() method in the subclass that has
the same signature as the __init__() method in the superclass. The subclass __init__() method can
then call the superclass __init__() method to initialize the properties of the superclass.
class Vehicle:
self.color = color
def show_info(self):
print("Vehicle Information:")
print("Color:", self.color)
class Car(Vehicle):
super().__init__(color)
self.brand = brand
def show_info(self):
print("Car Information:")
print("Color:", self.color)
print("Brand:", self.brand)
vehicle = Vehicle("Red")
Tha classes are that can also derived from class that already derived Here, the DerivedClass1 class is
derived from the SuperClass class, and the DerivedClass2 class is derived from the DerivedClass1
class.
It is class can also be derived from classes that are already derived.
If a class is derived from more than one base class called.. This means that the new class
inherits all the attributes and methods of its parent classes.
class Parent1:
def func1(self):
print("This is function 1 from Parent 1")
class Parent2:
def func2(self):
obj.func1()
obj.func2()
obj.func3()
def method(self):
class B(A):
def method(self):
class C(A):
def method(self):
pass
d = D()
Method overloading is a feature that allows a class to have multiple methods with the same name,
but different parameters... It allows a class to have multiple methods with the same name but
different functionalities based on the arguments passed.
class MathOperations:
def add(self, a, b, c):
return a + b + c
math = MathOperations()
Method overriding is a feature that allows a subclass to have a method with the same name and
signature as a method in its superclass. When a method is overridden, the subclass method will be
called instead of the superclass method.
class Animal:
def speak(self):
print("Animal speaks.")
class Dog(Animal):
def speak(self):
print("Dog barks.")
animal = Animal()
dog = Dog()
13.Explain the steps involved in creating a GUI application in Python with a suitable example.
1. Import the Tkinter module. This module provides the basic functionality for creating GUI
applications in Python.
2. Create a root window. The root window is the main window of the GUI application.
3. Add widgets to the root window. Widgets are the graphical elements that make up the GUI
application.
4. Bind events to the widgets. Events are the actions that users can perform on the widgets.
5. Enter the main event loop. The main event loop is responsible for handling user input and
updating the GUI application.
Eg:
import tkinter as tk
def say_hello():
print("Hello, world!")
root = tk.Tk()
button.pack()
root.mainloop()
14.How to create a button widget and bind it to the event handler? Explain with example.
When the user clicks on the push button, that 'clicking' event should be linked with the
'callback handler' function.Then only the button widget will appear as if it is performing
some task. As an example, let's bind the button click with the function as:
b.bind('<Button-1>', buttonClick)
A push button is a component that performs some action when clicked. These buttons are
created as objects of Button class as:
eg:
import tkinter as tk
def button_click():
print("Button clicked!")
root = tk.Tk()
button.bind("<Button-1>", button_click)
button.pack()
root.mainloop()
The bind() method is used to bind an event to a handler function. The <Button-1> event is the event
that is triggered when the user clicks the left mouse button on the button. The say_hello() function is
the handler function that is called when the <Button-1> event is triggered.
Once we create widgets or components, we can arrange them in the frame in a particular
manner. Arranging the widgets in the frame is called 'layout management'. There are three
types of layout managers.
The pack() method can take another option 'side' which is used to place the widgets side by
side. 'side' can take the values LEFT, RIGHT, TOP or BOTTOM. The default value is TOP. For
example,
import tkinter as tk
root = tk.Tk(
label1.pack(side=tk.LEFT)
label2.pack(side=tk.RIGHT)
button.pack()
root.mainloop()
Grid layout manager uses the grid() method to arrange the widgets in a two dimensional table that
contains rows and columns. We know that the horizontal arrangement of data is called 'row' and
vertical arrangement is called 'column'. The position of a widget is defined by a row and a column
number
import tkinter as tk
root = tk.Tk()
label1.grid(row=0, column=1)
label2.grid(row=0, column=2)
button.grid(row=0, column=3)
root.mainloop()
Place layout manager uses the place() method to arrange the widgets. The place() method takes x
and y coordinates of the widget along with width and height of the window where the widget has to
be displayed.
import tkinter as tk
root = tk.Tk()
label1.place(x=0, y=0)
label2.place(x=100, y=0)
button.place(x=100, y=50)
root.mainloop()
16.Explain the process of creating a Listbox widget with a suitable example. Also, explain different
values associated with selectmode option.
A list box is useful to display a list of items in a box so that the user can select 1 or more
items.To create a list box, we have to create an object of Listbox class, as:
import tkinter as tk
root = tk.Tk()
listbox = tk.Listbox(root)
listbox.pack()
root.mainloop()
values:
browse: Multiple items can be selected by clicking and dragging the mouse.
multiple: Multiple items can be selected by holding down the Ctrl key while
clicking the items
EXTENDED: We can select any adjacent group of items at once by clicking
on the first item and dragging to the last item.
Eg:
import tkinter as tk
root = tk.Tk()
listbox.pack()
root.mainloop()
Entry widget is useful to create a rectangular box that can be used to enter or display one
line of text. For example, we can display names, passwords or credit card numbers using
Entry widgets. An Entry widget can be created as an object of Entry class as:
import tkinter as tk
root = tk.Tk()
text = tk.Text(root)
text.pack()
root.mainloop()
Text widget is same as a label or message. But Text widget has several options and can
display multiple lines of text in different colors and fonts.
It is possible to insert text into a Text widget, modify it or delete it. We can also display
images in the Text widget. One can create a Text widget by creating an object to Text class as:
import tkinter as tk
root = tk.Tk()
entry = tk.Entry(root)
entry.pack()6
root.mainloop()