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

Gregory Heard
Gregory Heard
1,975 Points

How do i get this function to pass to the end return?

I am just confused about how i am getting integers to pass into my try block. I can get try blocks working easily when i can define the parameters. Also returning None on th except block... what does it do?

Thanks in advance!

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

2 Answers

Carlos Federico Puebla Larregle
Carlos Federico Puebla Larregle
21,074 Points

Actually you have to "try" to float them, if they can't be "parse" to float you return "None" in the "except" block. If the "except" block is never reach you return the addition of the two numbers.

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

I hope that helps a little bit

Gregory Heard
Gregory Heard
1,975 Points

Oh i see! So you use the act of trying to float the integers as your check. Thank you very much!