function is not returning what is intended

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


function is not returning what is intended



The function that I created is to measure the length of an argument!. I want to return "Sorry, integers don't have length"


def string_length(mystring):
if type(mystring) == int:
return "Sorry, integers don't have length"
else:
return len(mystring)

mystring = input("what is the value ?")
print(string_length(mystring))



what am I doing wrong?





You didn't pass it an int.
– user2357112
yesterday




2 Answers
2



Your question isn't very clear, but this should work, if my understanding is not wrong:


def string_length(mystring):
try:
if type(int(mystring)) == int:
return "Sorry, integers don't have length"
elif type(mystring) == str:
return len(mystring)
except:
return len(str(mystring))
mystring = input("what is the value ?")
print(string_length(mystring))





type(int(mystring)) == int is always true, though. I think you just masked the problem with a try-except
– cricket_007
yesterday




type(int(mystring)) == int



In Python2, input will evaluate to an integer, not a string, which would explain the message.


input



You can use hasattr to check for the __len__ magic function rather than doing explict type checking.


hasattr


__len__



This should work for any iterable type, I believe


def string_length(mystring):
if hasattr(mystring, '__len__'):
return len(mystring)
else:
print("Sorry, {} don't have length".format(type(mystring)))
return None

mystring = input("what is the value ?")
print(string_length(mystring))



Then, make sure you are running this in Python3






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Keycloak server returning user_not_found error when user is already imported with LDAP

PHP parse/syntax errors; and how to solve them?

How to scale/resize CVPixelBufferRef in objective C, iOS