0

I'm a new to Python and a piece of code doesn't seem to work as desired. Here is the code:

#Create a function that takes any string as argument and returns the length of that string. Provided it can't take integers.

def length_function(string):
    length = len(string)
    return length

string_input=input("Enter the string: ")
if type(string_input) == int:
    print("Input can not be an integer")
else:
    print(length_function(string_input))

Whenever I type an integer in the result, it gives me the the number of digits in that integer. However, I want to display a message that "Input can not be an integer".

Is there any error in my code or is there another way of doing this. Please respond. Thank You!

1
  • length_function is a bit redundant when you can call len directly. Also if you insist you can just do length_function = len Commented May 26, 2019 at 17:54

3 Answers 3

3

Any input entered is always string. It cannot be checked for int. It will always fail. You can do something like below.

def length_function(string):
    length = len(string)
    return length

string_input=input("Enter the string: ")
if string_input.isdigit():
    print("Input can not be an integer")
else:
    print(length_function(string_input))

Output:

Enter the string: Check
5

Enter the string: 1
Input can not be an integer
Sign up to request clarification or add additional context in comments.

2 Comments

Damn, you beat me to it :) Also, I think it is important to mention that entering 12345 gives the string '12345', not the integer 12345. Sounded like the problem only exists because that difference was unclear for the person asking the question.
@finomnis I did mention that in my answer but in different words Any input entered is always string.
1

I'm not sure why you're wrapping len() in your length_function but that's not necessary. The result of input() will always be a string so your if cannot evalue to true. To turn it into a number use int(). This will fail if the input can't be parsed into an integer, so rather than an if...else you probably want to do sth like

try:
    int(string_input)
    print("Input cannot be an integer")
except ValueError:
    print(length_function(string_input))

Comments

0

Even integers are taken as strings for example instead of 10 it is taking "10".

def RepresentsInt(s):
try: 
    int(s)
    return True
except ValueError:
    return False

def length_function(string):
length = len(string)
return length

string_input=input("Enter the string: ")
if RepresentsInt(String_input):
    print("Input can not be an integer")
else:
    print(length_function(string_input))

Comments

Your Answer

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.