0

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
asked Jul 25, 2018 at 20:56
1
  • 4
    You didn't pass it an int. Commented Jul 25, 2018 at 21:03

2 Answers 2

0

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
Sign up to request clarification or add additional context in comments.

1 Comment

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

In 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

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.