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

code not working

  1. Every block works fine, except "else" block Don't know why ?

  2. Why are we even giving the values while calling the function, even when it's asking the user to give those in Try block

trial.py
def add(n1,n2):
    try:
        n1 = float(input("Give First No: "))
        n2 = float(input("Give Second No: "))
        total = n1 + n2

    except ValueError:
        print(" U've given something wrong ! ")

    else:
        return("Sum of two Nos: = {}".format(total))

sum = add(10.3,10.8)

1 Answer

The code is perfectly correct. But with certain changes it'll pass.

Also, remember that these are automated script and you should not pass a single thing more than required.

def add(n1,n2):
    try:
        #No need to take the input, we already have arguments
        #n1 = float(input("Give First No: "))
        #n2 = float(input("Give Second No: "))
        total = n1 + n2

    except ValueError:
        print(" U've given something wrong ! ")

    else:
        #return only total
        return(total)