Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,073 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!