Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,307 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?