Python Forum

Full Version: new to coding
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi, I am doing a basic exercise in python were I have to call the function with a string as the value for the argument mystring and will return the length of that string. If an integer is passed as an input, the function should output a message like "Sorry, integers don't have length".

Here is my code:
def string_length(mystring):
    string = len(mystring)
    return string

mystring = input("Enter a String: ")

if (mystring) == int:
    print("Sorry, integers don't have length!")
    
else:
    print(string_length(mystring))
Here is one output when inputting a string:

Output:
Enter a String: hello 5
Here is another output when inputting an integer:

Output:
Enter a String: 100 3
Second output should be expecting to print "Sorry, integers don't have length!"

Hope you can help me with my concern.

Thank you.
Several things:

- input() always returns string
- even if you have integer, this comparison doesn't work as you expect:

>>> 3 == int
False
- your function doesn't output message as required in description
Thank you for the response.
The string method isdigit should do the trick here
>>> 'string'.isdigit()
False
>>> '12321'.isdigit()
True