My expectation is if typecasting is successful I need to get 'True'. If the typecasting is not successful, I need to get 'False'.
Let's say there is a list.
details_list = ["ramji",10, -12, "muthu", 20]
I want to check the value in each index whether it is an integer. If the value in each index is convertible to int, I should get 'True'. Otherwise, 'False'
Below is the code I tried.
def get_first_value(number_list):
counter = 0
while counter < len(number_list):
if int(number_list[counter]): # Getting error at this line.
counter = counter + 1
else:
return False
return number_list[0]
details_list = ["ramji",10, -12, "muthu", 20]
status = get_first_value(details_list)
print(status)
I get an error which is...
if bool(int(number_list[counter])):
ValueError: invalid literal for int() with base 10: 'ramji'
Please help me.
try/except
clause. Try something, if it raises an error do something else. - MathieuTrue
for already anint
, orTrue
for "is convertable toint
" (e.g."10"
isstr
and10.3
isfloat
, neither areint
, but callingint()
on them would produce10
in both cases)? - ShadowRangerint
, or if it can be converted to anint
? - Klaus D.isinstance
-based solution. shrugs - ShadowRanger