-2

I'm trying to build a code which executes the length of a string

This code should be able to accept only Strings and return their length but when integer or float values are given, it counts their length too.

def length(string):
    if type(string)== int:
        return "Not Available"
    elif type(string) == float:
        return "Not Allowed"
    else:
        return len(string)
string=input("Enter a string: ")
print(length(string))

Output:

Enter a string: 45
2
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Rahul Raj
  • 13
  • 2
  • The string will be a string, no matter what symbols it contains. It will not be an int or a float, no matter how much it looks like one. – Karl Knechtel Sep 10 '22 at 19:30

2 Answers2

1

You expect to get output 'Not Available' for the input 45. But it won't happen because, while reading input from keyboard default type is string. Hence, the input 45 is of type str. Therefore your code gives output 2.

Sreeram TP
  • 11,346
  • 7
  • 54
  • 108
1

input returns a string so if you check its type it will always be string. To check if its an int or a float you have to try to cast it.

try:
    int(input)
except ValueError:
    # not an int
    return "Not Available"

try:
   float(input)
except ValueError:
    # not a float
    return "Not Allowed"

return len(string)
Kami Kaze
  • 611
  • 3
  • 14