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

Refactoring Question

Is there a better way for me to clean this code? The break, break, and break at the end seems to be weird but it works.

count = 1
print("Please input 3 different numbers:")
while True:
    try:
        num1 = int(input("Pick your first number: "))
    except ValueError:
        print("That is not a number -- please try again.")
        continue
    else:
        count += 1
        while True:
            try:
                num2 = int(input("Pick your second number: "))
            except ValueError:
                print("That is not a number -- please try again.")
                continue
            else:
                while True:
                    count += 1
                    try:
                        num3 = int(input("Pick your third number: "))
                    except ValueError:
                        print("That is not a number -- please try again.")
                        continue
                    else:
                        max_num = max(num1, num2, num3)
                        min_num = min(num1, num2, num3)
                        average_total = (num1 + num2 + num3)/count
                        break
                break
        break
print("The largest number is:", max_num)
print("The smallest number is:", min_num)
print("The average of all {} numbers is {}".format(count, average_total))

I wanted that every prompt will throw an exception error without repeating back to the first prompt.

3 Answers

Steven Parker
Steven Parker
243,318 Points

Instead of creating infinite loops ("while True:") that you need to break out of, you can use a conditional statement in the "while" that determines when the loop should end.

I thought of that too, however that's where I am confused on how I can put a conditional with the try and except as they are somewhat a conditional :/

nevermind, I found it!!! Lol Thankss!

nums = []
print_messages = ["Pick your first number: ",
                  "Pick your second number: ",
                  "Pick your third number: "]
while True:
    try:
        current = int(input(print_messages[len(nums)]))
    except ValueError:
        print("That is not a number -- please try again.")
        continue

    nums.append(current)

    if len(nums) == 3:
        break

print ("The largest number is:", max(nums))
print ("The smallest number is:", min(nums))
print ("The average of all {} numbers is {}".format(len(nums), sum(nums)/float(len(nums))))
Steven Parker
Steven Parker
243,318 Points

You did a great job compacting, but you still use "break". To use my suggestion, you could eliminate the "if" and the "break" by revsersing the test and making it the 'while' condition:

while len(nums) < 3:

oh true, instead of adding that random if- statement at the end. Next time I should think about first if any user input be best putting in a list to avoid nesting, then use a while statement just like you did. Thanks!

I just tried the while len(nums), it gave me a type error: Object of type int has no len()

Steven Parker
Steven Parker
243,318 Points

That doesn't make sense, because your very first line clearly creates "nums" as a list, not an int:

nums = []