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

whats the difference

whats the difference between try and else

1 Answer

I assume that you want to know why you would care to use else in a try/except clause. Pardon me if I'm wrong.

Let's say that we get input (as a string) from a user, and we want to convert it into an integer. Of course, some mischievous user might enter some non-integer, such as "abc", and Python will throw an error. Not user-friendly at all!

Solution:

user_input = input('Enter a number: ')
try:
    num = int(user_input)
except ValueError:
    print('Please enter a number.')

Now, once the user types in a non-integer, we catch the error and respond with a more friendly message. But the user can't re-enter the number and have another chance! Let's use a loop.

while True:
    user_input = input('Enter a number: ')
    try:
        num = int(user_input)
        break
    except ValueError:
        print('Please enter a number.')

Now, this works, but most people reading this code would have to scratch their head a little bit to understand it. This is because break is in an awkward place: in the try block.

Of course, this is a matter of preference, but I (and many people) prefer to write:

while True:
    user_input = input('Enter a number: ')
    try:
        num = int(user_input)
    except ValueError:
        print('Please enter a number.')
    else:
        break

I hope this helps. ~Alex