Hive D. Desu Hive D. Desu - 5 months ago 6
Python Question

Need help understanding section of code

I wrote a piece of code, it was marked by an auto machine-bot.

We are not allowed to question this bot, its "100% correct".

I got 90%. Professor wont go over it, and we are "meant to" pay a higher year student to help us if we have troubles, because this is a basic level course.

Here is the code:

def something(placeholder):
"""
append intengers
"""
siba = list()
try:
for items in placeholder:
if int(items):
siba.append(int(items))
except ValueError:
pass
return siba


placeholder = ["123", "+142", "-39", "GRTG356", "x", "12-3", "123+"]
print(something(placeholder))


Can anyone tell me what I could have probably done to get 100%? This was the only section of code I got marked "0" for. I still get the same answer, its just the method is wrong.

Answer

Your error handling will currently return the list if a value inside can't be converted to a int. it should instead go to the next item.

def something(placeholder):
    """
    append intengers
    """
    siba = list()
    for items in placeholder:
        try:
            siba.append(int(items))
        except ValueError:
            pass
    return siba

If I supply your original code with ["123", "+142", "-39", "GRTG356", "x", '1', "12-3", "123+", '572'] it would return ["123", "+142", "-39"] when it should instead return [123, 142, -39, 1, 572]

Comments