Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python The Solution: While Loops

Maximiliane Quel
PLUS
Maximiliane Quel
Courses Plus Student 55,489 Points

Is it wrong to use the exception clause to end the game?

Hi,

is it a problem to use the exception clause to calculate the values, return a sentence and then quit the function? If so why?

Here is my code:

# Problem 2: Total and average
# Complete the following function so that it asks for
# number from the user until they enter 'q' to quit.
# When they quit, print out the list of numbers,
# then sum and the average of all of the numbers.

def total_and_average():
    numbers = []
    # Solution 2 here
    while True:
        try:
            num = int(input("What is your number? Press any key to stop entering numbers. "))
        except ValueError:
            total = sum(numbers)
            average = total/len(numbers)

            print(f'Your numbers were {numbers}, '
            f'their sum {total} is and their average {average}.')
            break

        else:
            numbers.append(num)

total_and_average()

1 Answer

Steven Parker
Steven Parker
231,269 Points

There's nothing wrong with the basic concept you described, but in this case it does not fulfill the conditions given in the instructions.

The instructions call for a function that "asks for number[s] from the user until they enter 'q' to quit.", but the exception would occur for any input that is not a number.

Maximiliane Quel
Maximiliane Quel
Courses Plus Student 55,489 Points

Okay thanks. I understand that I would break for any key entry but a numeric character. In my mind that would be okay though as I couldn't do anything with those entries either. I was just not sure about banking on catching an error to perform the intended tasks at the end of each game, if that makes sense.

Steven Parker
Steven Parker
231,269 Points

That part should be fine. But one other observation, the message "Press any key..." might be confusing since it usually implies a single keystroke will be responded to, but the "input" statement will wait on a return.