0

I'm a beginner and my function doesn't work. I don't what I missed in it:

def string_length(stri):
if stri == int:
   print(" not a string")
else:
   print(len(stri), stri)

stri = str(input("please write a string: "))
string_length(stri)

in a few, the if statement it's ignored if I write an integer.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • 2
    it's not that it's ignored. It's that what you think it's doing vs what it's actually doing is very different. stri == int is *not* how you check if something is *an* int. – Paritosh Singh Nov 09 '19 at 12:40
  • 1
    Your "if" tests if a particular object is equal to the integer type. That doesn't make sense here. You want "isinstance". – Michael Butscher Nov 09 '19 at 12:42
  • 1
    Also, note that your inputs are always going to be strings if you're accepting them from user. "3" and 3 are different. one is a string. – Paritosh Singh Nov 09 '19 at 13:06

1 Answers1

-1
def is_number(stri):
    try:
        float(stri)
        return True
    except ValueError:
        pass

def string_length(stri):
    if is_number(stri) == True:
       print(" not a string")
    else:
       print(len(stri), stri)

stri = input("please write a string: ")
is_number(stri)
string_length(stri)

It didn't work for you because a number can be in the form of a string, e.g "6" instead of 6. So any time you put in a number it would be a string and so would ignore the if. the is_number() function checks whether the string can be represented as a float and if so returns the value "True".

Syz_01
  • 13
  • 7