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 trialtangtai chen
4,844 Pointsi don't know how to apply try/except/else statement inside of a function
def add(x, y): try: except ValueError: return None else: x = float(x); y = float(y); return x + y
this is my code it doesn't seems right, can anyone help?
def add(x, y):
try:
except ValueError:
return None
else:
x = float(x); y = float(y);
return x + y
1 Answer
Christian Mangeng
15,970 PointsHi tangtai,
it could look like that (see below). "Try" checks if the provided numbers can be converted to floats. Note that try, except and else have the same indentation (one tab, because they are inside a function), and the actions that follow also have the same (+ 1 tab compared to try, except and else):
def add(num1, num2):
try:
float1 = float(num1)
float2 = float(num2)
except ValueError:
return None
else:
return float1 + float2
tangtai chen
4,844 Pointstangtai chen
4,844 PointsThx for the help, I was confused about the logic behind try/except/else statements, now it makes more sense to me!