-2

The program is to measure the length of a string that is entered, but if an integer is entered; it should print "undetectable".

This program should return the output of the if statement when it encounters an integer. Instead it just recognizes the else statement, even in the case of an integer. What could I be doing wrong here?

def string_length(mystring):
    if type(mystring) == int :
        return "undetectable"
    else:
        return len(mystring) 
mystring=input("Enter the string: ") 
print("The length of the string entered is: " + str(string_length(mystring)))
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Farhan
  • 3
  • 1
  • 1
    Your input is a string, so it won't ever be detected as an integer. – APhillips Jan 21 '20 at 21:13
  • 1
    The input is always a string, `type("1") != int`. – jonrsharpe Jan 21 '20 at 21:13
  • 2
    `input("Enter the string: ")` will always return a string, no matter what you enter: `1`, `hello` or `3.141`, so `mystring` (see - _string_!) will be a string. (Yes, the string here is made of string :D) – ForceBru Jan 21 '20 at 21:14
  • Does this answer your question? [How can I read inputs as numbers?](https://stackoverflow.com/questions/20449427/how-can-i-read-inputs-as-numbers) – AMC Jan 22 '20 at 00:46

3 Answers3

2

The function input will always return a string.

If the user enters 1, what you get in your variable is the string '1', not the integer 1. This is why your if condition never evaluates to True.

One way of checking if a string represents a (positive) integer would be to use isdigit():

if(mystring.isdigit()):
    return "undetectable"
Anis R.
  • 6,656
  • 2
  • 15
  • 37
1

The input() function always returns a string. Sometimes that string can represent an input, but you'd need to convert it first using int().

The usual way to check whether the string represents an integer is to try to interpret it as one, using try/except, and if that fails then assume it isn't:

def string_length(my_string):
    try:
        int_value = int(mystring)
        # if no error, then it's an integer
        return "undetectable"
    except ValueError:
        # error; converting it to an int failed. Must be a regular string.
        return len(my_string)

Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53
1

First, input returns a string, so the object will always be a string, even if it is a string of ascii characters that correspond with integers. You will want to use isdigit() to check if the string an integer.

if mystring.isdigit():
    return "undetectable"