Semantic Error using Conditionals statements

Question:

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
Asked By: Rahul Raj

||

Answers:

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.

Answered By: Sreeram TP

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)
Answered By: Kami Kaze
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.