1
votes

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.

3
Have a look into the try/except clause. Try something, if it raises an error do something else. - Mathieu
Please clarify: Is it True for already an int, or True for "is convertable to int" (e.g. "10" is str and 10.3 is float, neither are int, but calling int() on them would produce 10 in both cases)? - ShadowRanger
Thanks, @Mathieu . I am just a beginner. I didn't learn exception handling yet. Thanks for your advice. - K Ramji
Do you want to check if it is an int, or if it can be converted to an int? - Klaus D.
@Christoph: Sigh. Clearly they misrepresented the problem, since they accepted an isinstance-based solution. shrugs - ShadowRanger

3 Answers

0
votes

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)
0
votes

You need to catch the error raised by the int()method. Instead of if/else clause, use try/except

        try:
            int(number_list[counter])   # Getting error at this line.
            counter = counter + 1
        except ValueError:
            return False 

0
votes

Use a simple for loop with a try statement.

def get_first_value(number_list):
    for v in number_list:
        try:
            return int(v)
        except ValueError:
            pass
    return False

The first time you find a value for which int(v) successfully returns a number, return that number immediately. If you get a ValueError, ignore it and move on to the next value. Only if you exhaust all the values in the input without finding a number will you reach the final return False statement.

I would, however, suggest either returning None or raising an exception if no number if found. As a general rule, a function should always return values of a single type (the exception being to use None to represent "no value").


If, despite the name of your function, you want to return true if all vales are int, do the same thing, except return False in the event of an exception and return True at the end of the function.

def all_numbers(number_list):
    for v in number_list:
        try:
            int(v)
        except ValueError:
            return False
    return True