0% found this document useful (0 votes)
3 views19 pages

Unit 3 Python

The document outlines various aspects of file handling and object-oriented programming in Python, including supported file types, access modes, and the use of the 'with' statement for file operations. It also covers class definitions, constructors, inheritance, and methods for reading and writing data to files. Additionally, it explains concepts like operator overloading, GUI components in Tkinter, and the distinction between different widgets.

Uploaded by

pujarinidhi3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views19 pages

Unit 3 Python

The document outlines various aspects of file handling and object-oriented programming in Python, including supported file types, access modes, and the use of the 'with' statement for file operations. It also covers class definitions, constructors, inheritance, and methods for reading and writing data to files. Additionally, it explains concepts like operator overloading, GUI components in Tkinter, and the distinction between different widgets.

Uploaded by

pujarinidhi3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

2m:

1. List file types supported by Python. Give example for each

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)

2.List any four file access modes in Python.

“r” Opens the file in read only mode and this is the default mode.

“w” Opens the file for writing.

“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

“r+” Opens the file for both reading and writing.

“w+” Opens the file for reading and writing.

3.Give the syntax of with statement to open the file.

with open (file, mode) as file_handler:

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.

file_handler.name :It returns the name of the file.

5.What is use of seek() and tell() methods.

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

6. Give syntax of constructor definition in Python.

def __init__(self, parameter_1, parameter_2, …., parameter_n):

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

8. How to return object from a method ? Give example

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.

Eg: def sum(a,b):

return a+b

sum(5,15) #20

9. How to define private instance variables and methods in Python.

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):

self._private_var = 42 # Private instance variable

def _private_method(self):

print("This is a private method.")

def public_method(self):

print("This is a public method.")

self._private_method() # Accessing private method

obj = MyClass()

print(obj._private_var) # Accessing private variable

obj.public_method()

#42

#This is a public method.

#This is a private method.

10. What is multipath inheritance ?

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.

Eg: class Person:

def __init__(self, name):

self.name = name

class Student(Person):

def __init__(self, name, school):

super().__init__(name)

self.school = school

student = Student("John Doe", "Stanford University")

print(student.name) # Output: John Doe

print(student.school) # Output: Stanford University

12. Give the general syntax of multiple inheritance.

class DerivedClassName(Base_1, Base_2, Base_3):

<statement-1>

.
<statement-N>

13. What is operator Overloading ?

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:

def __init__(self, X):

self.X = X

# adding two objects

def __add__(self, U):

return self.X + U.X

object_1 = example( int( input("Please enter the value: ")))

object_2 = example( int( input("Please enter the value: ")))

print ("the sum is:", object_1 + object_2)

14.What is root window? How it is created in Python?

 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.

Eg: import tkinter as tk

root = tk.Tk()

root.title("My Application")

root.geometry("500x300")

root.mainloop()

15.What is Canvas? How it is created in Python?

 A canvas is a rectangular area which can be used for drawing pictures like lines, circles,
polygons, arcs, etc.

 To create a canvas, we should create an object to Canvas class as:

c = Canvas(root, bg="blue", height=500, width=600, cursor='pencil')

16.Differentiate Canvas and frame


Feature Canvas Frame

Purpose Drawing pictures or other complex layouts Grouping widgets together

Features Can draw shapes, lines, text, and images Cannot draw shapes, lines, text, or images

Usage Creating GUIs Grouping widgets together

17.How to add a scrollbar to a Text widget?

import tkinter as tk

from tkinter import scrolledtext

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()

18.Differentiate Label and Text Widget.

Feature Label Text

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

Usage Displaying static text Displaying dynamic text


19.What is an entry widget? How it is created?

 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:

e1 = Entry(f, width=25, fg='blue', bg='yellow', font=('Arial', 14), show='*')

20.What is a spin box widget? How it is created?

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.

s1 = Spinbox(f, from_= 5, to=15, textvariable=val1, width=15, fg='blue', bg='yellow', font=('Arial',


14, 'bold'))

21.List the values that can be assigned to selectmode property of listbox

 SINGLE ,BROWSE ,MULTIPLE ,EXTENDED

4m

1. List and explain various file opening modes with examples.

 r - Open a file for reading. This is the default mode.

Eg: f = open("myfile.txt", "r")

 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.

Eg: f = open("myfile.txt", "w")

f.write("This is a new file.")

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.

Eg: f = open("myfile.txt", "a")

f.write("This is new data.")

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.

Eg:f = open("myfile.txt", "r+")

f.write("This is new data.")

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.

Eg: f = open("myfile.txt", "w+")

f.write("This is new data.")

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:

print("File already exists.")

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

Eg: with open("myfile.txt", "r") as f:

content = f.read()

print(content)

 with - This is the keyword that starts the with statement.

 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+.

 as f - This is the as keyword. It assigns the file object to the variable f.

 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

Using the read() method

The read() method reads the entire contents of a file and returns it as a string.

Syntax: file_handler. read([size])

Eg:

def read_file(filename):

with open(filename, "r") as f:

content = f.read()
return content

content = read_file("myfile.txt")

print(content)

Using the readlines() method

The readlines() method reads the contents of a file line by line and returns a list of strings.

Syntax: file_handler.readlines() Eg:

def read_file(filename):

with open(filename, "r") as f:

lines = f.readlines()

return lines

lines = read_file("myfile.txt")

for line in lines:

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.

Syntax: file_handler. write(string)

Eg:def write_file(filename, content):

with open(filename, "w") as f:

f.write(content)

write_file("myfile.txt", "This is my data.")

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.

Syntax: file_handler. writelines(sequence)

def write_file(filename, lines):

with open(filename, "w") as f:

f.writelines(lines)

lines = ["This is my data.", "This is another line."]

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.

filename = input("Enter file name: ")


with open(filename, 'r') as f:

wordcount = {}

for word in f.read().split():

if word not in wordcount:

wordcount[word] = 1

else:

wordcount[word] += 1

print("Occurrences of each word:")

for key, value in wordcount.items():

print(key, value)

print("\nNumber of words in the file:", sum(wordcount.values()))

output: Enter file name: star.txt

Occurrences of each word:

hi 2

hello 1

star 1

Number of words in the file: 4

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

Syntax: object_name = ClassName(argument_1, argument_2, ….., argument_n)

The constructor is a special method that is called when an object is created. It is used to initialize the
object’s data.

Syntax: def __init__(self, parameter_1, parameter_2, …., parameter_n):

statement(s) eg:
class Person:

def __init__(self, name):

self.name = name

class Student(Person):

def __init__(self, name, school):

super().__init__(name)

self.school = school

student = Student("John Doe", "Stanford University")

print(student.name) # Output: John Doe

print(student.school) # Output: Stanford University

7. What is inheritance? How to implement inheritance in Python? Give an example

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:

# Base class attributes and methods

class DerivedClass(BaseClass):

# Derived class attributes and methods

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()

d.bark() # dog barking

d.speak() #animal speaking


8. Explain with example overriding superclass constructor and method

In Python, overriding a superclass constructor or method means redefining the constructor or


method in the subclass so that it has a different implementation. This can be used to change the
behavior of the constructor or method in the subclass.

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:

def __init__(self, color):

self.color = color

def show_info(self):

print("Vehicle Information:")

print("Color:", self.color)

class Car(Vehicle):

def __init__(self, color, brand):

super().__init__(color)

self.brand = brand

def show_info(self):

print("Car Information:")

print("Color:", self.color)

print("Brand:", self.brand)

# Creating objects of the derived class

vehicle = Vehicle("Red")

car = Car("Blue", "Toyota")

# Calling overridden methods

vehicle.show_info() # Output: Vehicle Information: Color: Red

car.show_info() # Output: Car Information: Color: Blue, Brand: Toyota

9. Explain multi-level inheritance with example

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.

10.Explain multiple inheritance in Python with an example.

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):

print("This is function 2 from Parent 2"


class Child(Parent1, Parent2): #class derviedclassname(bas1,basee2,base3):
def func3(self):
print("This is function 3 from Child")
obj = Child()

obj.func1()
obj.func2()
obj.func3()

11.Explain multipath inheritance with example.


class A:

def method(self):

print("Method of class A")

class B(A):

def method(self):

print("Method of class B")

class C(A):

def method(self):

print("Method of class C")

class D(B, C):

pass

# Creating an object of class D

d = D()

# Calling the method

d.method() # Method of class B

12.Explain method overloading and overriding with example

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()

print(math.add(2, 3, 4)) # Output: 9

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()

animal.speak() # Output: Animal speaks.

dog.speak() # Output: Dog barks.

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 = tk.Button(root, text="Say Hello", command=say_hello)

button.pack()
root.mainloop()

 import tkinter as tk - This imports the Tkinter module.

 root = tk.Tk() - This creates a root window.

 button = tk.Button(root, text="Say Hello", command=say_hello) - This creates a button with


the text "Say Hello". The command parameter specifies the function that will be called when
the button is clicked.

 button.pack() - This packs the button into the root window.

 root.mainloop() - This enters the main event loop.

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:

b = Button(f, text='My Button', width=15, height=2, bg='yellow', fg='blue',


activebackground='green', activeforeground='red')

eg:

import tkinter as tk

def button_click():

print("Button clicked!")

root = tk.Tk()

button = tk.Button(root, text="Click Me", command=button_click)

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.

15.Write a note on arranging Widgets in a frame using layout managers.

 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.

Pack layout manager


Grid layout manager

Place layout manager

 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 = tk.Label(root, text="Label 1")

label2 = tk.Label(root, text="Label 2")

button = tk.Button(root, text="Button"

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 = tk.Label(root, text="Label 1")

label2 = tk.Label(root, text="Label 2")

button = tk.Button(root, text="Button")

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 = tk.Label(root, text="Label 1")


label2 = tk.Label(root, text="Label 2")

button = tk.Button(root, text="Button"

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:

 lb = Listbox(f, font=(‘Arial’, ’12’,’ bol’), fg='blue', bg='yellow', height=8, width=24,


activestyle='underline', selectmode=MULTIPLE)

import tkinter as tk

root = tk.Tk()

listbox = tk.Listbox(root)

listbox.insert(1, "Item 1")

listbox.insert(2, "Item 2")

listbox.insert(3, "Item 3")

listbox.pack()

root.mainloop()

values:

 single: Only one item can be selected at a time.

 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 = tk.Listbox(root, selectmode="multiple")

listbox.insert(1, "Item 1")


listbox.insert(2, "Item 2")

listbox.insert(3, "Item 3")

listbox.pack()

root.mainloop()

17.Write a note on i) Text Widget ii) Entry Widget

 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:

e1 = Entry(f, width=25, fg='blue', bg='yellow', font=('Arial', 14), show='*')

import tkinter as tk

root = tk.Tk()

text = tk.Text(root)

text.insert(tk.END, "This is a multiline text area.")

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:

t = Text(root, width=20, height=10, font=('Verdana', 14, 'bold'), fg='blue', bg='yellow',


wrap=WORD)

import tkinter as tk

root = tk.Tk()

entry = tk.Entry(root)

entry.pack()6

root.mainloop()

You might also like