TypeError: 'int' object is not iterable, apperars when I try to add a string into a list

Viewed 43

This code creates 2 lists, one contains every number passed in and the second one contains the indexes of one of these four symbols +-*$.

Why do I have the problem mentioned in the title?

def calculate(string: str):
    allowed_symboles = "1234567890+-*$"
    symbole_sum = len(string)
    symbole_sum0 = 0

    for symbole in string:
        for lol in allowed_symboles:
            if symbole == lol:
                symbole_sum0 += 1

    if symbole_sum != symbole_sum0:
        return "400: Bad request"

    all_numbers = []
    pos_of_operators = []

    for x, num in zip(string, range(0, len(string))):
        if x != "+" and x != "-" and x != "*" and x != "$":
            all_numbers += x
        else:
            pos_of_operators += num

    print(all_numbers, pos_of_operators)

calculate("1231241+4234")
1 Answers

there are many ways to add elements to list in python, append(__element__) if one of them:

my_list = []
my_list.append(1)
print(my_list)

would return: [1]

Also I suggest a better way to check if all the element in the input string are in the allowed_symbols, check it out:

def calculate(string:str):

    allowed_symboles: str = "1234567890+-*$"

    for i in string:
        if not (i in allowed_symboles):
            return "400: Bad Request"
    

    all_numbers = []
    pos_of_operators = []

    for x, num in zip(string, range(0, len(string))):
        if x != "+" and x != "-" and x != "*" and x != "$":
            all_numbers.append(x)
        else:
            pos_of_operators.append(num)

    print(all_numbers, pos_of_operators)

calculate("1231241+4234")
Related