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) Logic in Python Try and Except

natalia iaroslavskaia
natalia iaroslavskaia
7,293 Points

indentation for TRY block inside a function

What are the rules for inserting a TRY block into a function

trial.py
def add(first, second):
        try:
            first=int(input("Give the first number"))
            second=int(input("Give the second number"))
        except ValueError:
             return None
        else:
            first=float(first)
             second=float(second)
            return first+second
Adam Ryde
Adam Ryde
5,222 Points

im no expert by any means, but the indentation in your else block for second=float(second) looks one space to many... i dont know if this helps mate

2 Answers

james south
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
james south
Front End Web Development Techdegree Graduate 33,271 Points

indentation-wise, you are close. it should look like this:

def add(first, second):
    try:
        first=int(input("Give the first number"))
        second=int(input("Give the second number"))
    except ValueError:
        return None
    else:
        first=float(first)
        second=float(second)
        return first+second

that is, def statement at the left edge, try, except and else indented at the same level (here, 4 spaces), and then their respective bodies indented at the same level (here, 4 more spaces). this challenge does not ask for user input, so you need to remove that. the function takes 2 arguments, you have first and second, those are passed in when the function is called, no need to ask for user input. in the try block you are TRY-ing to cast them as floats. if it works, the else block executes, so return the sum. if the cast to float does not work, the except executes, return None.