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 Python Basics (2015) Number Game App Squared

Daniel Petrov
Daniel Petrov
3,495 Points

can we have two try catches in one function and how we relate them?

not sure how to make this one working. tried different ways. when I test it and call the function in workspaces it returns "name 'arg' is not defined" even though I set it up as an input.

squared.py
# EXAMPLES
# squared(5) would return 25
# squared("2") would return 4
# squared("tim") would return "timtimtim"
def squared(arg):
    try:
        arg = int(arg)
    except ValueError:
        return(arg * len(arg))
    try:
        arg = str(arg)
    except ValueError:
        return(arg ** 2)

1 Answer

Ryan Ruscett
Ryan Ruscett
23,309 Points

You can have a try that does several things, and you can attempt to catch multiple exceptions. But you done put two try excepts inside a single function.

If you have to do a try and except, it's most likely because you know of an opportunity for failure. This opportunity arises because you are performing an action. If you have two try and excepts in one function. It would mean you are trying two actions that could fail in the same function. This would be cause enough to break out the work into two functions.

When you try something, you could receive different exceptions. So you can do a try and except multiple exceptions. This is done by separating them with a comma or using multiple except statements.

Does this help at all?