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

Marko Jakovljevic
Marko Jakovljevic
1,286 Points

ValueError: could not convert string to float: '2.25.2'

Seem to be having an error here when trying this out. The code compiles fine and adds a floating decimal point when I run this through my compiler

Not sure why it's coming up as a string? Have tried int() and have also tried to run float(num1) float(num2)

prior to the return

trial.py
def add(num1,num2):
  return(float(num1 + num2))

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,454 Points

If the arguments are strings, using float(num1 + num2), will concatenate the strings before trying to convert. Try this:

def add(num1,num2):
  return float(num1) + float(num2)
Melanie Villela
Melanie Villela
3,048 Points

Hello Chris,

Can you also write:

def add float(num1, num2):
    return (num1 + num2)
Chris Freeman
Chris Freeman
Treehouse Moderator 68,454 Points

Hi Melanie, the simple answer is no because it is a syntax error in the definition of a function.

The complicated answer is there is an advanced python feature called decorators where you can wrap a function with another function. This wrapping function can convert the passed arguments to other types such as floats.

You will see this when you reach the Flask Basics course. The @app.route() decorator can cast values from the URL into ints and floats.