UNIT II Question Bank With Answer
UNIT II Question Bank With Answer
UNIT II Question Bank With Answer
UNIT II
PART B (4 Marks)
1 How is KeyListener used to handle keypress event?
• We will be using the pynput module to listen to keyboard events. To install this
module execute pip install pynput in cmd.
• In python pynput (python module to detecting any key press) . “pynput.keyboard”
contains classes for controlling and monitoring the keyboard.
• It Calls pynput.keyboard.Listener. stop from anywhere, or return False from a
callback to stop the listener. This library allows you to control and monitor input
devices.
Approach:
• Import key, Listener from pynput.keyboard
• Create a with Statement: The with statement is used to wrap the execution of a block
with methods defined by a context manager.
Example 1:
from pynput.keyboard import Key, Listener
from pynput.keyboard import Key, Listener
def show(key):
print('\nYou Entered {0}'.format( key))
if key == Key.delete:
# Stop listener
return False
# Collect all event until released
with Listener(on_press = show) as listener:
listener.join()
2
List and define the three participants in an event
Event Handlers: Event handlers is a type of function or method that run a specific action
when a specific event is triggered. For example, it could be a button that when user click it,
it will display a message, and it will close the message when user click the button again, this
is an event handler.
Trigger Functions: Trigger functions in event-driven programming are a function that
decide what code to run when there are a specific event occurs, which are used to select
which event handler to use for the event when there is specific event occurred.
Events: Events include mouse, keyboard and user interface, which events need to be
triggered in the program in order to happen, that mean user have to interacts with an object
in the program, for example, click a button by a mouse, use keyboard to select a button and
etc.
3
List the declarative statements in declarative programming with examples.
Declarative Statements:
SQL Commands
The SQL commands help in creating and managing the database. The most common SQL
commands which are highly used are mentioned below:
1. CREATE command: used to create the new database, new table, table view, and
other objects of the database.
2. UPDATE command: used to update or change the stored data in the database.
3. DELETE command : used to remove the saved records from the database tables. It
erases single or multiple tuples from the tables of the database.
4. SELECT command : used to access the single or multiple rows from one or multiple
tables of the database. We can also use this command with the WHERE clause.
5. DROP command :used to delete the entire table, table view, and other objects from
the database
6. INSERT command : used to insert the data or records into the database tables.
4
Write a Python program that creates a Timer that will explode in 2 seconds using
TURTLE module.
import time
import turtle
window = turtle.Screen()
window.tracer(0)
player = turtle.Turtle()
timer_text = turtle.Turtle()
start = time.time()
while time.time() - start < 3:
player.forward(1)
player.left(1)
timer_text.clear()
timer_text.write(int(time.time() - start), font=("Courier", 30))
window.update()
turtle.done()
5
Illustrate the invoking of a descriptor using _ _getattribute()_ _ method.
Python descriptors are created to manage the attributes of different classes which use the
object as reference. In descriptors we used three different methods that are __getters__(),
__setters__(), and __delete__(). If any of those methods are defined for an object, it can
be termed as a descriptor.
6 Bring out the differences between Lists and Tuples in Python using examples.
Lists and Tuples store one or more objects or values in a specific order. The objects stored
in a list or tuple can be of any type including the nothing type defined by the None
Keyword.
1. The literal syntax of tuples is shown by parentheses () whereas the literal syntax
of lists is shown by square brackets [] .
2. Lists has variable length, tuple has fixed length.
3. List has mutable nature, tuple has immutable nature.
4. List has more functionality than the tuple.
Syntax
Syntax of list and tuple is slightly different. Lists are surrounded by square brackets []
and Tuples are surrounded by parenthesis ().
Example
list_num = [1,2,3,4]
tup_num = (1,2,3,4)
print(list_num)
print(tup_num)
list_num[2] = 5
print(list_num)
tup_num[2] = 5
Output :
[1,2,5,4]
Traceback (most recent call last):
File "python", line 6, in <module>
TypeError: 'tuple' object does not support item assignment
7
Using Turtle, Write a Python program to demonstrate Keypress Events. the turtle on the
screen must move according to the arrow keys (Up,Left,Right and Back) pressed.
def up():
tim.setheading(90)
tim.forward(100)
def down():
tim.setheading(270)
tim.forward(100)
def left():
tim.set_heading(180)
tim.forward(100)
def right():
tim.setheading(0)
tim.forward(100)
tim.listen()
tim.onkey(up, "Up") # This will call the up function if the "Left" arrow key is pressed
tim.onkey(down, "Down")
tim.onkey(left, "Left")
tim.onkey(right, "Right")
8
Compare and contrast imperative programming and declarative programming.
Imperative Programming
1. In this, programs specify how it is to be done.
2. It simply describes the control flow of computation.
3. Its main goal is to describe how to get it or accomplish it.
4. Its advantages include ease to learn and read, the notional model is simple to
understand, etc.
5. Its type includes procedural programming, object-oriented programming, parallel
processing approach.
6. In this, the user is allowed to make decisions and commands to the compiler.
7. It has many side effects and includes mutable variables as compared to declarative
programming.
8. It gives full control to developers that are very important in low-level
programming.
Declarative Programming
1. In this, programs specify what is to be done.
2. It simply expresses the logic of computation.
3. Its main goal is to describe the desired result without direct dictation on how to
get it.
4. Its advantages include effective code, which can be applied by using ways, easy
extension, high level of abstraction, etc.
5. Its type includes logic programming and functional programming.
6. In this, a compiler is allowed to make decisions.
7. It has no side effects and does not include any mutable variables as compared to
imperative programming.
8. It may automate repetitive flow along with simplifying code structure.
1
Discuss about an Event object and steps to handle an event
will display a message, and it will close the message when user click the button again, this is
an event handler.
Trigger Functions: Trigger functions in event-driven programming are a function that decide
what code to run when there are a specific event occurs, which are used to select which event
handler to use for the event when there is specific event occurred.
Events: Events include mouse, keyboard and user interface, which events need to be triggered
in the program in order to happen, that mean user have to interacts with an object in the
program, for example, click a button by a mouse, use keyboard to select a button and etc.
Tkinter is a Python library which is used to create GUI-based application. Tkinter comes with
many inbuilt features and extensions which can be used to optimize the application
performance and behaviour. Tkinter Events are generally used to provide an interface that
works as a bridge between the User and the application logic. We can use Events in any
Tkinter application to make it operable and functional.
Fundamental structure of tkinter program
1. Import tkinter package and all of its modules.
2. Create a root window. Give the root window a title (using title ()) and dimension
(using geometry ()). All other widgets will be inside the root window.
3. Use mainloop() to call the endless loop of the window. If you forget to call this
nothing will appear to the user. The window will wait for any user interaction till we
close it.
2
Design the Students information system with student details, qualification details and mark
details and add insert, delete and update button. Write an event handler to send the marks
to their parents, immediately after the mark has been updated.
3
Elaborate on the features of declarative programming and list the set of declarative
statements.
4
Write a Python program to create three states Solid, Liquid and Gas. Create transitions
Melt, Evaporate, Sublimate and Ionize with an exit callback printing the transition name.
5
Compare imperative programming with declarative programming.
PART B (4 Marks)
Program:
queue = []
MAX_NUM = 10
condition = Condition()
class ProducerThread(Thread):
def run(self):
nums = range(5)
global queue
while True:
condition.acquire()
if len(queue) == MAX_NUM:
print "Queue full, producer is waiting"
condition.wait()
print "Space in queue, Consumer notified the producer"
num = random.choice(nums)
queue.append(num)
print "Produced", num
condition.notify()
condition.release()
time.sleep(random.random())
class ConsumerThread(Thread):
def run(self):
global queue
while True:
condition.acquire()
if not queue:
print "Nothing in queue, consumer is waiting"
condition.wait()
print "Producer added something to queue and notified the consumer"
num = queue.pop(0)
print "Consumed", num
condition.notify()
condition.release()
time.sleep(random.random())
ProducerThread().start()
ConsumerThread().start()
OUTPUT:
Produced 0
Consumed 0
Produced 0
Produced 4
Consumed 0
Consumed 4
Nothing in queue, consumer is waiting
Produced 4
Producer added something to queue and notified the consumer
Consumed 4
Produced 3
Produced 2
Consumed 3
2 Implement the concept “Pool class” by importing a package pool
3 Write a python program to implement the dining philosopher problem.
Program
import time
import threading
class Philosopher(threading.Thread):
def __init__(self, pid, sticks, stomachCapacity=3):
threading.Thread.__init__(self)
self.pid = pid
self.sticks = sticks
self.amount = 0
self.stomachCapacity = stomachCapacity
def run(self):
if self.pid%2 == 0:
self.run_even()
else:
self.run_odd()
def run_even(self):
# Even philosophers are greedy and always wait for the next chopstick and
# never put down a chopstick until they have eaten.
i1 = pid
i2 = (pid + 1)%len(sticks)
print "Philosopher " + str(self.pid) + " is waiting for the first stick"
self.sticks[i1].acquire()
print "Philosopher " + str(self.pid) + " gets the left stick"
print "Philosopher " + str(self.pid) + " waits for the second stick"
self.sticks[i2].acquire()
print "Philosopher " + str(self.pid) + " has acquired the right stick"
self.amount += 1
print "Philosopher " + str(self.pid) + " eats"
self.sticks[i2].release()
print "Philosopher " + str(self.pid) + " has released the right stick"
self.sticks[i1].release()
print "Philosopher " + str(self.pid) + " has released the left stick"
def run_odd(self):
# Odd numbered philosophes are generous. If they cannot get the second stick
# they will put down the first and wait to try again.
i1 = self.pid
i2 = (self.pid + 1)%len(self.sticks)
# setting the argument to False makes it so that the thread is not locked and instead
# the acquire method returns a boolean for whether that thrread got the lock or not.
print "Philosopher " + str(self.pid) + " is trying to pick up the left stick."
if self.sticks[i1].acquire(False):
print "Philosopher " + str(self.pid) + " has picked up the left stick."
print "Philosopehr " + str(self.pid) + " is trying to pick up the right stick"
if self.sticks[i2].acquire(False):
print "Philosopher " + str(self.pid) + " picked up the right stick"
self.amount += 1
print "Philosopher " + str(self.pid) + " has eaten"
self.sticks[i2].release()
print "Philosopher " + str(self.pid) + " has released the right stick"
self.sticks[i1].release()
print "Philosopher " + str(self.pid) + " has released the left stick"
else:
print "Philosopher " + str(self.pid) + " has failed to get the second stick and released the left stick"
print "Philosopher " + str(self.pid) + " is waiting to try again."
self.sticks[i1].release()
time.sleep(0.1)
self.run()
else:
print "Philosopher " + str(self.pid) + " has failed to get the first stick and waits to try again."
time.sleep(0.1)
self.run()
numPhilosophers = 5
sticks = []
philosophers = []
for i in xrange(numPhilosophers):
sticks.append(threading.Lock())
amounts.append(0)
print "Finished!"
Output
Philosopher 0 is waiting for the first stickPhilosopher 1 is trying to pick up the left stick.
Philosopher 3 is trying to pick up the left stick.Philosopher 0 gets the left stickPhilosopher 2 is
waiting for the first stickPhilosopher 1 has picked up the left stick.
Philosopher 0 has acquired the right stickPhilosopehr 1 is trying to pick up the right stick
Philosopher 0 eats
Philosopher 0 has released the right stickPhilosopher 1 picked up the right stick
Philosopher 0 has released the left stick
Philosopher 1 has eatenPhilosopher 2 gets the left stickPhilosopher 3 has picked up the left stick.
Philosopher 2 waits for the second stickPhilosopher 1 has released the right stick
Philosopher 1 has released the left stickPhilosopher 2 has acquired the right stickPhilosopher 4 is
waiting for the first stickPhilosopehr 3 is trying to pick up the right stick
Philosopher 2 eatsPhilosopher 3 has failed to get the second stick and released the left stick