Issue
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.
Solution
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.
Answered By - kabanus
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.