1

I am working on a class assignment in which I need to raise two exceptions. First Exception: I am supposed to raise and handle an exception if a user's entry is less than 0 or greater than 100. The code should then ask the user for the digit again.

Second Exception: If a particular file is not found, the exception requests the file name and then search happens again.

In both cases, I cannot make the exception happen. In other words, if in the first exception, I enter a digit greater than 100 or less 0, the program continues and simply doesn't record anything for this entry. If I print the user's entry, I get "none" rather than the error message that the except clause should display. Likewise in the second exception, if the file is not found, the code simply stops executing rather than firing the exception.

I have tried manually raising an exception (as in this question/answer), but that creates a traceback which I do not want-- I just want the first exception to print the error message and call a function and the second to request input and call a function.

First exception:

def grade():
    #input student's average grade
    avgGrade = int(input("Enter average grade: "))
    try:
        if avgGrade > 0 and avgGrade < 100:
            return avgGrade
    except ValueError:
        print("Grade must be numeric digit between 0 and 100")
        grade()

Second exception:

def displayGrades(allStudents):
    try:
        #open file for input
        grade_file = open(allStudents, "r")

        #read file contents
        fileContents = grade_file.read()

        #display file contents
        print(fileContents)

        grade_file.close()

    except IOError:
        print("File not found.")
        allStudents = input("Please enter correct file name: ")
        displayGrades(allStudents)
Community
  • 1
  • 1
momExMachina
  • 111
  • 1
  • 3

3 Answers3

2

Sounds like the exercise is to raise the exception and handle it. You really need a loop for continuation rather than recursion, e.g.:

def grade():
    while True:
        try:
            avgGrade = int(input("Enter average grade: "))
            if avgGrade < 0 or avgGrade > 100:
                raise ValueError()
        except ValueError:
            print("Grade must be numeric digit between 0 and 100")
            continue # Loop again
        break # Exit loop
    return avgGrade

But this is contrived for the purpose of the exception, as exceptions are not really needed in this case.

For your other example this is less contrived because the downstream function raises the exception, e.g.:

def displayGrades(allStudents):
    while True:
        try:
            with open(allStudents, "r") as grade_file:
               ...
        except IOError:
            allStudents = input("Please enter correct file name: ")
            continue
        break

Though I would caution mixing arg passing and user input in the same function - usually the exception would be caught and handled where the user is originally providing the file name. So in this example, it would probably be the calling function.

AChampion
  • 29,683
  • 4
  • 59
  • 75
  • I agree that the first is contrived, but it's specific to the homework assignment. Thanks for the caution on the second but again, the assignment says "exception should cause program to ask for correct file name" -- the file name having already been specified earlier in the program, but not by the user. thanks much – momExMachina Oct 28 '16 at 02:19
1

For your first one, you have to raise it manually as python won't guess your logic and raise it for you.

def grade():
    #input student's average grade
    avgGrade = int(input("Enter average grade: "))
    try:
        if avgGrade > 0 and avgGrade < 100:
            return avgGrade
        else:
            raise ValueError()      
    except ValueError:
        print("Grade must be numeric digit between 0 and 100")
        return grade()

For the second one, You have to return the value in the second call. use return displayGrades(allStudents) instead of displayGrades(allStudents)

Shady Atef
  • 2,121
  • 1
  • 22
  • 40
  • Can you fix your indentation? Also, `IOError` still exists as a synonym for `OSError` in python 3. – tdelaney Oct 28 '16 at 01:43
  • thanks for the heads up, my text book uses IO, but I'd rather use whatever term is more common. – momExMachina Oct 28 '16 at 02:22
  • Shady Atef, when I implement this code, I receive the error message and the request for a new number. But then the same thing happens as with my previous code: the new number is not returned and when printed, displays as "none". – momExMachina Oct 28 '16 at 02:41
  • The idea is that you use recursive calls, and don't return the value of the second `grade()` call. It will be the same case with second one – Shady Atef Oct 28 '16 at 02:43
0

Try this:

def get_value(data_list, index):
    return data_list[index]

# Sample list data
my_list = ['a', 'b', 'c']
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
  • 1
    While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – Kevin M. Mansour Aug 24 '21 at 00:56