Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

1. Please write the following Python 3 Program. Please show all output. Exceptio

ID: 3788696 • Letter: 1

Question

1. Please write the following Python 3 Program. Please show all output.

Exceptions Lab¶

Improving input

The input() function can generate two exceptions: EOFError or KeyboardInterrupt on end-of-file(EOF) or canceled input.

Create a wrapper function, perhaps safe_input() that returns None rather rather than raising these exceptions, when the user enters ^C for Keyboard Interrupt, or ^D (^Z on Windows) for End Of File.

Update your mailroom program to use exceptions (and IBAFP) to handle malformed numeric input

Explanation / Answer

import signal
import sys
def signal_handler(signal, frame):
print('You pressed Ctrl+C!')
  
signal.signal(signal.SIGINT, signal_handler)
line=sys.stdin.readline()
if line:
print('hie')
else:
print('you pressed Ctrl+D')
signal.pause()

output:

sh-4.3$ python main.py                                                                                                                                   

^CYou pressed Ctrl+C!

sh-4.3$ python main.py                                                                                                                                   

you pressed Ctrl+D

explaination:

Ctrl + C was handled by using the signal. handlers which uses SIGNINT(signal number for Ctrl+C) and calls the signal_handler function when the user press the Ctrl+C

Ctrl+D was handled by reading the line using sys.stdin.readline() method and then checks whether the line is present and if the line is not there which means Ctrl+D then it will print that 'you pressed Ctrl+D'. By this way, we can handle Ctrl+C and Ctrl+D without using exception handlers