PYTHON QUESTIONS, KUMUD ALOK, ASSISTANT PROFESSOR
Q1 Define various file modes in python?
Q2 Explain about read () function in python.
This method is used to read a specified number of bytes of data from a data file.
The syntax of read() method is:
file_object.read(n)
Consider the following set of statements to understand the usage of read() method:
>>>myobject=open("myfile.txt",'r')
>>> myobject.read(10)
'Hello ever'
>>> myobject.close()
Q3 Explain Packages in python with example
Packages are a way of structuring Python’s module namespace by using “dotted
module names”. For example, the module name A.B designates a submodule
named B in a package named A.
Example:
Suppose you want to design a collection of modules (a “package”) for the uniform
handling of sound files and sound data. There are many different sound file formats
(usually recognized by their extension, for example: .wav, .aiff, .au), so you
may need to create and maintain a growing collection of modules for the
conversion between the various file formats. There are also many different
operations you might want to perform on sound data (such as mixing, adding echo,
applying an equalizer function, creating an artificial stereo effect), so in addition
you will be writing a never-ending stream of modules to perform these operations.
Here’s a possible structure for your package (expressed in terms of a hierarchical
filesystem):
PYTHON QUESTIONS, KUMUD ALOK, ASSISTANT PROFESSOR
Users of the package can import individual modules from the package, for
example:
import sound.effects.echo
This loads the submodule sound.effects.echo. It must be referenced
with its full name.
sound.effects.echo.echofilter(input, output, delay=0.7,
atten=4)
An alternative way of importing the submodule is:
from sound.effects import echo
This also loads the submodule echo, and makes it available without its
package prefix, so it can be used as follows:
echo.echofilter(input, output, delay=0.7, atten=4)
Q4 What do you understand by IDE in python?
PYTHON QUESTIONS, KUMUD ALOK, ASSISTANT PROFESSOR
An integrated development environment (IDE) is a program dedicated to
software development. As the name implies, IDEs integrate several tools
specifically designed for software development. These tools usually include:
An editor designed to handle code (with, for example, syntax
highlighting and auto-completion)
Build, execution, and debugging tools
Some form of source control
Most IDEs support many different programming languages and contain
many more features.
Q5 Define operators in python. Explain with an example of each.
PYTHON QUESTIONS, KUMUD ALOK, ASSISTANT PROFESSOR
PYTHON QUESTIONS, KUMUD ALOK, ASSISTANT PROFESSOR
Q6 What do you mean by precedence in python? Explain the role of precedence
with an example.
An expression in python consists of variables, operators, values, etc. When the
Python interpreter encounters any expression containing several operations, all
operators get evaluated according to an ordered hierarchy, called operator
precedence.
Q7 Describe the file handling procedure in detail. Write a python code to
create a file with ‘Data.txt’ name and write name and roll no of 10
students and then read this file to print it.
# Open the file in write mode
with open("Data.txt", "w") as f:
# Write the names and roll numbers of 10 students
PYTHON QUESTIONS, KUMUD ALOK, ASSISTANT PROFESSOR
for i in range(10):
name = input("Enter student name: ")
roll_no = input("Enter student roll number: ")
f.write(f"{name}, {roll_no}\n")
# Close the file
f.close()
# Open the file in read mode
with open("Data.txt", "r") as f:
# Read the contents of the file
data = f.read()
# Print the contents of the file
print(data)
# Close the file
f.close()
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:
PYTHON QUESTIONS, KUMUD ALOK, ASSISTANT PROFESSOR
file_object = open(file_name, mode)
Here, file_name is the name of the file or the location of the file that you
want to open, and file_name should have the file extension included as well.
Which means in test.txt – the term test is the name of the file and .txt is the
extension of the file.
The mode in the open function syntax will tell Python as what operation you
want to do on a file.
‘r’ – Read Mode: Read mode is used only to read data from
the file.
‘w’ – Write Mode: This mode is used when you want to write
data into the file or modify it. Remember write mode overwrites
the data present in the file.
‘a’ – Append Mode: Append mode is used to append data to
the file. Remember data will be appended at the end of the file
pointer.
‘r+’ – Read or Write Mode: This mode is used when we want
to write or read the data from the same file.
‘a+’ – Append or Read Mode: This mode is used when we
want to read data from the file or append the data into the
same file.
Note: The above-mentioned modes are for opening, reading or writing text
files only.
While using binary files, we have to use the same modes with the
letter ‘b’ at the end. So that Python can understand that we are interacting
with binary files.
‘wb’ – Open a file for write only mode in the binary format.
‘rb’ – Open a file for the read-only mode in the binary format.
‘ab’ – Open a file for appending only mode in the binary
format.
‘rb+’ – Open a file for read and write only mode in the binary
format.
‘ab+’ – Open a file for appending and read-only mode in the
binary format.
Python Read From File
In order to read a file in python, we must open the file in read mode.
PYTHON QUESTIONS, KUMUD ALOK, ASSISTANT PROFESSOR
There are three ways in which we can read the files in python.
read([n])
readline([n])
readlines()
Here, n is the number of bytes to be read.
The read () method
This method is used to read a specified number of bytes of data from a data file.
The syntax of read() method is:
file_object.read(n)
The readline([n]) method
This method reads one complete line from a file where each line terminates
with a newline (\n) character. It can also be used to read a specified number
(n) of bytes of data from a file but maximum up to the newline character (\n).
In the following example, the second statement reads the first ten
characters of the first line of the text file and displays them on the screen.
The readlines() method
The method reads all the lines and returns the lines along with newline as a
list of strings. The following example uses readlines() to read data from the
text file myfile.txt.
After opening the file, we can use the following methods to write data in the
file.
• write() - for writing a single string
• writelines() - for writing a sequence of strings
PYTHON QUESTIONS, KUMUD ALOK, ASSISTANT PROFESSOR
The write() method
write() method takes a string as an argument and writes it to the text file. It
returns the number of characters being written on single execution of the
write() method. Also, we need to add a newline character (\n) at the end of
every sentence to mark the end of line.
The writelines() method
This method is used to write multiple strings to a file. We need to pass an
iterable object like lists, tuple, etc. containing strings to the writelines()
method. Unlike write(), the writelines() method does not return the number
of characters written in the file. The following code explains the use of
writelines().
Q8 What is “GUI” and “GUI calculator using tkinter python”?
The tkinter package (“Tk interface”) is the standard Python interface to
the Tcl/Tk GUI toolkit. Both Tk and tkinter are available on most Unix
platforms, including macOS, as well as on Windows systems.
PYTHON QUESTIONS, KUMUD ALOK, ASSISTANT PROFESSOR
Architecture
Tcl/Tk is not a single library but rather consists of a few distinct modules,
each with separate functionality and its own official documentation. Python’s
binary releases also ship an add-on module together with it.
Tcl
Tcl is a dynamic interpreted programming language, just like Python.
Though it can be used on its own as a general-purpose programming
language, it is most commonly embedded into C applications as a
scripting engine or an interface to the Tk toolkit. The Tcl library has a
C interface to create and manage one or more instances of a Tcl
interpreter, run Tcl commands and scripts in those instances, and
add custom commands implemented in either Tcl or C. Each
interpreter has an event queue, and there are facilities to send events
to it and process them. Unlike Python, Tcl’s execution model is
designed around cooperative multitasking, and Tkinter bridges this
difference (see Threading model for details).
Tk
Tk is a Tcl package implemented in C that adds custom commands
to create and manipulate GUI widgets. Each Tk object embeds its
own Tcl interpreter instance with Tk loaded into it. Tk’s widgets are
very customizable, though at the cost of a dated appearance. Tk
uses Tcl’s event queue to generate and process GUI events.
Ttk
Themed Tk (Ttk) is a newer family of Tk widgets that provide a much
better appearance on different platforms than many of the classic Tk
widgets. Ttk is distributed as part of Tk, starting with Tk version 8.5.
Python bindings are provided in a separate module, tkinter.ttk.
Internally, Tk and Ttk use facilities of the underlying operating
system, i.e., Xlib on Unix/X11, Cocoa on macOS, GDI on
Windows.
When your Python application uses a class in Tkinter, e.g., to
create a widget, the tkinter module first assembles a Tcl/Tk
command string. It passes that Tcl command string to an
internal _tkinter binary module, which then calls the Tcl
interpreter to evaluate it. The Tcl interpreter will then call into
the Tk and/or Ttk packages, which will in turn make calls to
Xlib, Cocoa, or GDI.
Tkinter Modules
Support for Tkinter is spread across several modules. Most
applications will need the main tkinter module, as well as
PYTHON QUESTIONS, KUMUD ALOK, ASSISTANT PROFESSOR
the tkinter.ttk module, which provides the modern themed
widget set and API:
from tkinter import *
from tkinter import ttk
# Python program to create a simple GUI
# calculator using Tkinter
# import everything from tkinter module
from tkinter import *
# globally declare the expression variable
expression = ""
# Function to update expression
# in the text entry box
def press(num):
# point out the global expression variable
global expression
# concatenation of string
expression = expression + str(num)
# update the expression by using set method
equation.set(expression)
# Function to evaluate the final expression
def equalpress():
# Try and except statement is used
# for handling the errors like zero
# division error etc.
# Put that code inside the try block
# which may generate the error
try:
global expression
# eval function evaluate the expression
# and str function convert the result
# into string
total = str(eval(expression))
equation.set(total)
# initialize the expression variable
PYTHON QUESTIONS, KUMUD ALOK, ASSISTANT PROFESSOR
# by empty string
expression = ""
# if error is generate then handle
# by the except block
except:
equation.set(" error ")
expression = ""
# Function to clear the contents
# of text entry box
def clear():
global expression
expression = ""
equation.set("")
# Driver code
if __name__ == "__main__":
# create a GUI window
gui = Tk()
# set the background colour of GUI window
gui.configure(background="light green")
# set the title of GUI window
gui.title("Simple Calculator")
# set the configuration of GUI window
gui.geometry("270x150")
# StringVar() is the variable class
# we create an instance of this class
equation = StringVar()
# create the text entry box for
# showing the expression .
expression_field = Entry(gui, textvariable=equation)
# grid method is used for placing
# the widgets at respective positions
# in table like structure .
expression_field.grid(columnspan=4, ipadx=70)
# create a Buttons and place at a particular
# location inside the root window .
# when user press the button, the command or
# function affiliated to that button is executed .
PYTHON QUESTIONS, KUMUD ALOK, ASSISTANT PROFESSOR
button1 = Button(gui, text=' 1 ', fg='black', bg='red',
command=lambda: press(1), height=1,
width=7)
button1.grid(row=2, column=0)
button2 = Button(gui, text=' 2 ', fg='black', bg='red',
command=lambda: press(2), height=1,
width=7)
button2.grid(row=2, column=1)
button3 = Button(gui, text=' 3 ', fg='black', bg='red',
command=lambda: press(3), height=1,
width=7)
button3.grid(row=2, column=2)
button4 = Button(gui, text=' 4 ', fg='black', bg='red',
command=lambda: press(4), height=1,
width=7)
button4.grid(row=3, column=0)
button5 = Button(gui, text=' 5 ', fg='black', bg='red',
command=lambda: press(5), height=1,
width=7)
button5.grid(row=3, column=1)
button6 = Button(gui, text=' 6 ', fg='black', bg='red',
command=lambda: press(6), height=1,
width=7)
button6.grid(row=3, column=2)
button7 = Button(gui, text=' 7 ', fg='black', bg='red',
command=lambda: press(7), height=1,
width=7)
button7.grid(row=4, column=0)
button8 = Button(gui, text=' 8 ', fg='black', bg='red',
command=lambda: press(8), height=1,
width=7)
button8.grid(row=4, column=1)
button9 = Button(gui, text=' 9 ', fg='black', bg='red',
command=lambda: press(9), height=1,
width=7)
button9.grid(row=4, column=2)
button0 = Button(gui, text=' 0 ', fg='black', bg='red',
command=lambda: press(0), height=1,
width=7)
button0.grid(row=5, column=0)
PYTHON QUESTIONS, KUMUD ALOK, ASSISTANT PROFESSOR
plus = Button(gui, text=' + ', fg='black', bg='red',
command=lambda: press("+"), height=1,
width=7)
plus.grid(row=2, column=3)
minus = Button(gui, text=' - ', fg='black', bg='red',
command=lambda: press("-"), height=1,
width=7)
minus.grid(row=3, column=3)
multiply = Button(gui, text=' * ', fg='black', bg='red',
command=lambda: press("*"),
height=1, width=7)
multiply.grid(row=4, column=3)
divide = Button(gui, text=' / ', fg='black', bg='red',
command=lambda: press("/"),
height=1, width=7)
divide.grid(row=5, column=3)
equal = Button(gui, text=' = ', fg='black', bg='red',
command=equalpress, height=1, width=7)
equal.grid(row=5, column=2)
clear = Button(gui, text='Clear', fg='black', bg='red',
command=clear, height=1, width=7)
clear.grid(row=5, column='1')
Decimal= Button(gui, text='.', fg='black', bg='red',
command=lambda: press('.'), height=1,
width=7)
Decimal.grid(row=6, column=0)
# start the GUI
gui.mainloop()
PYTHON QUESTIONS, KUMUD ALOK, ASSISTANT PROFESSOR
Q9 Describe about matplotlib.
Matplotlib library is used for creating static, animated, and interactive 2D- plots or figures
in Python. It can be installed using the following pip command from the command prompt:
pip install matplotlib
For plotting using Matplotlib, we need to import its Pyplot module using the following
command:
import matplotlib.pyplot as plt
plt is an alias or an alternative name for matplotlib.pyplot. We can use any other alias also.
The pyplot module of matplotlib contains a collection of functions that can
be used to work on a plot. The plot() function of the pyplot module is used to
create a figure. A figure is the overall window where the outputs of pyplot
functions are plotted. A figure contains a plotting area, legend, axis labels,
ticks, title, etc. Each function makes some change to a figure: example,
creates a figure, creates a plotting area in a figure, plots some lines in a
plotting area, decorates the plot with labels, etc. It is always expected that
the data presented through charts easily understood. Hence, while
presenting data we should always give a chart title, label the axis of the
chart and provide legend in case we have more than one plotted data. To
plot x versus y, we can write plt.plot(x,y). The show() function is used to
display the figure created using the plot() function. Let us consider that in a
city, the maximum temperature of a day is recorded for three consecutive
days. Program 4-1 demonstrates how to plot temperature values for the
given dates. The output generated is a line chart.
PYTHON QUESTIONS, KUMUD ALOK, ASSISTANT PROFESSOR
Q10 Define Lambda function with example.
A lambda function is a small anonymous function.
A lambda function can take any number of arguments, but can only have
one expression.
The syntax of a lambda function is
lambda args: expression
Q11 Write a Python program to construct the following pattern, using a
nested for loop.
PYTHON QUESTIONS, KUMUD ALOK, ASSISTANT PROFESSOR
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*