Home > Software design >  How to get boolean result of a typecasting in python?
How to get boolean result of a typecasting in python?

Time:07-28

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.

CodePudding user response:

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)

CodePudding user response:

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 

CodePudding user response:

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
  • Related