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
srikanth soma
1,572 Pointsconvert str to int?
def squared(num):
try:
if num == int(num):
return num * num
except ValueError:
str1 = len(num) * num
return str1
I know we can convert string to int using python built-in int but when I added additional elif block to the above code like this elif str1 == int(num):
return str1 * str1 but I get error as unable to squared may I know what I'm doing wrong?
3 Answers
Steven Parker
243,318 PointsYou're not actually saving the converted int anywhere. You just compare it to the original argument (which is not actually desirable or necessary).
On the other hand, if you were to convert it and save it back in the same variable ("num = int(num)"), then the next line would be guaranteed to multiply numbers.
srikanth soma
1,572 PointsI didn't understand completely what you're saying can you please rewrite those changes in my code so that I know what you're saying
Steven Parker
243,318 PointsWhat I was saying is essentially to replace this line (which compares the argument with the converted version of itself):
if num == int(num):
With this one, which replaces the argument with the converted version:
num = int(num)
And then you'd just need to fix the indentation on the "return" statement that follows.
srikanth soma
1,572 PointsGot it thanks :)