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

Garrett Phipps
PLUS
Garrett Phipps
Courses Plus Student 2,808 Points

Python: Basics 'try' and 'except' Code Challenge

This function works in workspaces. I saved it as a script, and ran it in the shell just fine. Put in two numbers, got the answer as a float. However the challenge is telling me that Task 1 no longer works. Task 1 answer looks like this:

def add(count1, count2): return(count1 + count2)

I don't understand how the addition suddenly doesn't work. In Task 2 you add the float in the return(), and then Task 3 you're supposed to do this. I don't understand why it's not accepted. Could someone please explain what I'm apparently missing?

trial.py
def add(count1, count2):
    try:
        count1 = int(input("Give me a number: "))
        count2 = int(input("Give me another: "))
    except ValueError:
        return(None)
    else:
        return(float(count1) + float(count2))
Garrett Phipps
Garrett Phipps
Courses Plus Student 2,808 Points

The Task 1 function I gave in the question is supposed to have two lines with proper whitespace... I don't know why it didn't display properly...

1 Answer

Josh Keenan
Josh Keenan
20,315 Points

You got your solution a bit mixed up there, here's mine.

def add(num1, num2):
  try:
    num1 = float(num1) 
    num2 = float(num2)
  except ValueError:
    return None
  else:
    num = num1 + num2
  return num

In the final task you need to try to convert the numbers to floats, then return none if there is an exception.

Else, return the two non converted numbers added together.

Garrett Phipps
Garrett Phipps
Courses Plus Student 2,808 Points

AHAA! That makes the challenge's wording make sooo much more sense! Thanks so much! I knew there was another way to write it, I just couldn't figure it out for the life of me!

Josh Keenan
Josh Keenan
20,315 Points

It happens to all of us, don't worry it gets easier but everyone will always make some mistakes.