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

RMZ .
RMZ .
1,002 Points

Try and Except

I'm confused how to set the float () function on this function. Can someone please help me out? Many thanks and appreciate it!

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

2 Answers

Antonio De Rose
Antonio De Rose
20,885 Points
# your challenge 1 is correct
def add (num1, num2):
    return num1 + num2 # have to convert to float # hint is given in the question on how to convert # challenge 2
add (float(10, 15)) #this line is not required

# then for the last task, use try and except
Sneha Nagpaul
Sneha Nagpaul
10,124 Points

I see how you can consider float(some_var) a function call, which it is. But try to think about it as changing the type of some_var (type casting). So, it should take only one argument as a function call. Thus, this idea of float() taking multiple arguments is invalid.

some_var = '5'
float(some_var). # 5.0

some_var = 'a'
float(some_var) # Will throw a ValueError

Now that we know that we are trying to type cast, you want to be able to check if what was sent to the function is indeed something numeric inside the function. If it isn't, it will throw a ValueError, which you must catch with the try-except-else block.