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?
Mahir Islam
1,7002 gold badges16 silver badges33 bronze badges
-
4You didn't pass it an int.user2357112– user23571122018年07月25日 21:03:34 +00:00Commented Jul 25, 2018 at 21:03
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))
answered Jul 25, 2018 at 23:04
Mahir Islam
1,7002 gold badges16 silver badges33 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
OneCricketeer
type(int(mystring)) == int is always true, though. I think you just masked the problem with a try-exceptIn Python2, input will evaluate to an integer, not a string, which would explain the message.
You can use hasattr to check for the __len__ magic function rather than doing explict type checking.
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
answered Jul 25, 2018 at 23:16
OneCricketeer
193k20 gold badges147 silver badges277 bronze badges
Comments
lang-py