Reputation: 13
Well I'm very very new to python programming and still learning.So I tried to create a function where I used len to count the number of letters in a string.But since, len doesn't work for integers I set up conditionals so that it would return a message saying "integers don't have length". But I'm not getting the message even when I type an integer. please help me to solve this. here is my code:
def Length_String(L):
if type(L) == int:
return "sorry,integers don't have length"
else:
return len(L)
x = input()
y = Length_String(x)
print(y)
It's not that important but still I want to know what is causing the conditional not to work. please help me.
Upvotes: 1
Views: 58
Reputation: 25895
Note you can always type help(whatever)
in a Python prompt to read some useful stuff about it:
input(...)
input([prompt]) -> string Read a string from standard input. The trailing newline is stripped. If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError. On Unix, GNU readline is used if enabled. The prompt string, if given, is printed without a trailing newline before reading.
So you always get a string. One way to see if this string could be converted to an integer is:
try:
int(L)
return "Error, this is an integer!"
except ValueError:
return len(L)
Of course, this won't work for floats, so there maybe more checks you want to do (or just use float(L)
). Another way
if L.isnumeric(): # or isdigit or isdecimal
return "Error, this is a number!"
return L
Here it's worth mention that in addition to the help which can show methods you can always type dir(something)
in a Python prompt so see some useful methods in a list.
Upvotes: 2
Reputation: 6056
In Python input()
returns string no matter what you enter. So you don't need to check if the entered value is an int
. If you still want to check it, you could do it with isinstance
function:
if isinstance(L, int):
return "sorry,integers don't have length"
Upvotes: 1
Reputation: 405715
They input
function in Python returns a value of type str
even if what you type in is an integer value.
Upvotes: 2