How to make a return statement in python if the argument is a string that represents a valid integer?

Question:

if I write a main program to test its functions def as_integer(an_object) and def main()

If the argument is a string that represents a valid integer return that integer. Otherwise, return the NoneType object.

Call the as_integer function for each element in the list: [’20’, 10, len, True, ‘-six’, ‘-10’, ‘0’] and output the result object on its own line
I should get the following output:

OUTPUTS:

20
None
None
None
None
-10
0

I developed the following code but i’m still getting an error.

I tried only the first part of my code and got [’20’, 10, len, True, ‘-10’, ‘0’] to print as [20, 10, len, True, -10, 0] on separate lines. but without the quotes. Would that be a problem?

I’m unsure if to use the (isinstance) or (isdigit). I tried using the (isdigit) to detect if an_object is a digit or (startswith) a "-" but I would get an error. This is what i have so far. Also, thank you for your patience throughout all this.

def main():
    my_list = ['20', 10, len, True, '-10', '0']
    for an_object in my_list:
        print(as_integer(my_list))

def as_integer(an_object):
    if isinstance(an_object, (str, int)):
        return int(an_object)
    else:
        return None

I get this error:

#TEST 1#
main() returned None
inputs:

outputs:
**  ERROR  ** None
* EXPECTED * 20
None
None
None
None
**  ERROR  ** None
* EXPECTED * -10
**  ERROR  ** no line
* EXPECTED * 0
----------
#TEST 2#
** ERROR **as_integer(True) returned 1
* EXPECTED * None
inputs:

outputs:
----------
#TEST 3#
as_integer('43') returned 43
inputs:

outputs:
----------
#TEST 4#
as_integer('-50') returned -50
inputs:

outputs:
----------
#TEST 5#
as_integer(id) returned None
inputs:

outputs:
----------
Asked By: user18370003

||

Answers:

def as_integer(value):
    if isinstance(value, str):
        try:
            return int(value)
        except ValueError:
            return None
    return None

This would return None for as_integer(10), but maybe it’s your usecase. Still you can expand the condition with isinstance(value, (str, int)), but this will let True be converted to 1 which is common and expected in many more programming languages. For fixing this corner case you could add and value not in (True, False)

Answered By: Dmytro O

Here is an explanation of the function. You have to use .isdecimal to check if the object is or not a decimal. Then, you create a for loop inside the main function to call several times the as_integer function:

def as_integer(an_object):
if type(an_object) == str:
    if an_object.startswith('-'):
        newOb = an_object.split('-')
        if newOb[1].isdecimal():
            return int(an_object)
            #print(an_object)
        else:
            return None
    elif an_object.isdecimal():
        return int(an_object)
        #print(an_object)
    else:
        return None
else:
    return None

def main():
    my_list = ['20', 10, len, True, '-six', '-10', '0']
    for i in my_list:
        print(as_integer(i))
Answered By: David Borja
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.