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!

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

Christian Geib
Christian Geib
826 Points

How do I achieve floating numbers here

Hi, so this is my answer:

def add(num1, num2): return(float(num1+num2))

I receive a value error along the lines that it cannot convert floats to strings. What am I missing? Am I supposed to work with 'try:' or 'except' at this stage?

def add(num1, num2):

1 Answer

Michael Hulet
Michael Hulet
47,909 Points

In Python, operators and functions are evaluated from the inside out. Take this line of code for example:

result = float(num + other_num)

This adds the values of num and other_num, then converts it to a float, and assigns the result to result. However, this is different:

result = float(num) + float(other_num)

This converts num to a float, converts other_num to a float, then adds the two together, and then assigns it to result

Your code looks morel like my first example. It's adding values as-is, and then converts the result to a float. If the challenge passes in types that are incompatible for math (a string and a float, for example), your code will fail. I think what you meant to do is something more like my second example, so if you make it look like that, your code won't crash anymore