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

Question: Write a function that uses inputNumber to input a number from the keyb

ID: 3619701 • Letter: Q

Question

Question: Write a function that uses inputNumber to input a number
from the keyboard and that handles the ValueError exception.
--
The reading for the above question is below:
---
Exceptions:

Whenever a runtime error occurs, it creates an exception. Usually, the program
stops and Python prints an error message.

For example, dividing by zero creates an exception:

>>> print 55/0
ZeroDivisionError: integer division or modulo

So does accessing a nonexistent list item:

>>> a = []
>>> print a[5]
IndexError: list index out of range

Or accessing a key that isn’t in the dictionary:

>>> b = {}
>>> print b[’what’]
KeyError: what

Or trying to open a nonexistent file:

>>> f = open("Idontexist", "r")
IOError: [Errno 2] No such file or directory: ’Idontexist’

In each case, the error message has two parts: the type of error before the colon,
and specifics about the error after the colon. Normally Python also prints a
traceback of where the program was, but we have omitted that from the examples.

Sometimes we want to execute an operation that could cause an exception, but
we don’t want the program to stop. We can handle the exception using the try
and except statements.

For example, we might prompt the user for the name of a file and then try to
open it. If the file doesn’t exist, we don’t want the program to crash; we want to
handle the exception:

filename = raw_input(’Enter a file name: ’)
try:
   f = open (filename, "r")
except IOError:
   print ’There is no file named’, filename

The try statement executes the statements in the first block. If no exceptions
occur, it ignores the except statement. If an exception of type IOError occurs,
it executes the statements in the except branch and then continues.
We can encapsulate this capability in a function: exists takes a filename and
returns true if the file exists, false if it doesn’t:
def exists(filename):
   try:
      f = open(filename)
      f.close()
      return True
   except IOError:
      return False
You can use multiple except blocks to handle different kinds of exceptions. The
Python Reference Manual has the details.
If your program detects an error condition, you can make it raise an exception.
Here is an example that gets input from the user and checks for the value 17.
Assuming that 17 is not valid input for some reason, we raise an exception.
def inputNumber () :
   x = input (’Pick a number: ’) if x == 17 :
   raise ValueError, ’17 is a bad number’
return x
The raise statement takes two arguments: the exception type and specific information about the error. ValueError is one of the exception types Python provides
for a variety of occasions. Other examples include TypeError, KeyError, and my
favorite, NotImplementedError.
If the function that called inputNumber handles the error, then the program can
continue; otherwise, Python prints the error message and exits:
>>> inputNumber ()
Pick a number: 17
ValueError: 17 is a bad number
The error message includes the exception type and the additional information you
provided. Question: Write a function that uses inputNumber to input a number
from the keyboard and that handles the ValueError exception.
--
The reading for the above question is below:
---
Exceptions:

Whenever a runtime error occurs, it creates an exception. Usually, the program
stops and Python prints an error message.

For example, dividing by zero creates an exception:

>>> print 55/0
ZeroDivisionError: integer division or modulo

So does accessing a nonexistent list item:

>>> a = []
>>> print a[5]
IndexError: list index out of range

Or accessing a key that isn’t in the dictionary:

>>> b = {}
>>> print b[’what’]
KeyError: what

Or trying to open a nonexistent file:

>>> f = open("Idontexist", "r")
IOError: [Errno 2] No such file or directory: ’Idontexist’

In each case, the error message has two parts: the type of error before the colon,
and specifics about the error after the colon. Normally Python also prints a
traceback of where the program was, but we have omitted that from the examples.

Sometimes we want to execute an operation that could cause an exception, but
we don’t want the program to stop. We can handle the exception using the try
and except statements.

For example, we might prompt the user for the name of a file and then try to
open it. If the file doesn’t exist, we don’t want the program to crash; we want to
handle the exception:

filename = raw_input(’Enter a file name: ’)
try:
   f = open (filename, "r")
except IOError:
   print ’There is no file named’, filename

The try statement executes the statements in the first block. If no exceptions
occur, it ignores the except statement. If an exception of type IOError occurs,
it executes the statements in the except branch and then continues.
We can encapsulate this capability in a function: exists takes a filename and
returns true if the file exists, false if it doesn’t:
def exists(filename):
   try:
      f = open(filename)
      f.close()
      return True
   except IOError:
      return False
You can use multiple except blocks to handle different kinds of exceptions. The
Python Reference Manual has the details.
If your program detects an error condition, you can make it raise an exception.
Here is an example that gets input from the user and checks for the value 17.
Assuming that 17 is not valid input for some reason, we raise an exception.
def inputNumber () :
   x = input (’Pick a number: ’) if x == 17 :
   raise ValueError, ’17 is a bad number’
return x
The raise statement takes two arguments: the exception type and specific information about the error. ValueError is one of the exception types Python provides
for a variety of occasions. Other examples include TypeError, KeyError, and my
favorite, NotImplementedError.
If the function that called inputNumber handles the error, then the program can
continue; otherwise, Python prints the error message and exits:
>>> inputNumber ()
Pick a number: 17
ValueError: 17 is a bad number
The error message includes the exception type and the additional information you
provided.

Explanation / Answer

def inputNumber():
x = input('Pick a number: ')
if x == 17:
    raise ValueError, '17 is a bad number'
return x

def inputValidNumber():
try:
    num = inputNumber()
    print 'You picked ' + str(num) + '.'
except ValueError:
    print '17 is a bad number, please pick a new number.'
    inputValidNumber()

inputValidNumber()
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote