Issue
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.
Solution
You can try/except:
try:
int_value = int(number_list[counter])
counter = counter + 1
except ValueError:
return False
Or you can use isinstance
:
is_int = isinstance(number_list[counter], int)
Answered By - Lorenzo Bonetti
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.