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

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?

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

1 Answer

Michael Hulet
Michael Hulet
47,842 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