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 trialMykiel Horn
4,014 PointsHow come my function doesn't take in any number that I use as an argument in a string?
In this function I am trying to have to outcomes of: squared("tim") #will return timtimtim squared(2) #will return 4 squared("4") #will return 16
Everything works until I place "4" into my arguments. After hours of searching through the internet I still couldn't find an answer. But I eventually just played around with somethings and I figured it out. But I was just wondering how come the int() function doesn't work when I place a string of numbers in it?
arg = "squared"
def squared(arg):
try:
if arg == int(arg):
print(arg ** 2)
except ValueError:
print(arg * len(arg))
squared("4")
1 Answer
AJ Salmon
5,675 PointsBecause arg
is not equal to int(arg)
. With your example, that'd compare the string '4' to the integer 4, and the == comparator checks exact equality. A string and an integer can't be exactly equal, they're different class types, so it won't print. But because there's no ValueError
, it won't print the string either, so it does nothing. Hopefully this clears it up a bit! :)