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

chris Roach
chris Roach
3,475 Points

i think im writing this code right but its not giving me anything

i feel like ive got this code all set up correctly to finish the problem but its just not working

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

2 Answers

Zach Swift
Zach Swift
17,984 Points

I think he was looking for just a try except. You could just try returning the added floats at first and if there is an exception, then return None.

def add(num1, num2):
  try:
    return float(num1) + float(num2)
  except ValueError:
    return None
Tobias Helmrich
Tobias Helmrich
31,602 Points

Hey Chris,

you almost got it right! The only problem in your code is your indentation. In particular the indentation in your try and else blocks. If you indent everything correctly there it should work just fine! :)

Like so:

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

I hope that helps, good luck! :)