Home > Software design >  Why does this class method generate a TypeError?
Why does this class method generate a TypeError?

Time:09-23

I am writing a class to create a mathematical sequence, however, when I call the class methods getValueRange or getValueList, I get a TypeError for, seemingly, appending to the nums list.

Here is the class definition:

class Sequence:
    def __init__(self, term: str, var: str):
        self.term = term
        self.var = var

    def getValueAt(self, pos: int) -> int:
        return int(eval(self.term.replace(self.var, str(pos))))

    def getValueRange(self, pos1: int, pos2: int) -> list:
        nums = []

        for i in range(pos1, pos2):
            nums  = self.getValueAt(i)

        return nums

    def getValueList(self, pos_list: list):
        nums = []

        for i in pos_list:
            nums  = self.getValueAt(int(i))

        return nums


sq = Sequence("5*x-6", "x")
print(sq.getValueAt(1))
print(sq.getValueAt(2))
print(sq.getValueRange(4, 44))
print(sq.getValueList([5, 9, 27]))

Here is my error:

  File "C:\Users\USERNAME\PycharmProjects\Wistfully\main.py", line 29, in <module>
    print(sq.getValueRange(4, 44))
  File "C:\Users\USERNAME\PycharmProjects\Wistfully\main.py", line 13, in getValueRange
    nums  = self.getValueAt(i)
TypeError: 'int' object is not iterable

I have tried commenting out the appending to nums list in both functions and just printed out the results, which worked perfectly. I debugged all variables, and I am most definitely missing something.

CodePudding user response:

You wrote (roughly) this:

        nums = []
        ...
            nums  = 7

That won't work, as the integer 7 is not an iterable container.

You could use nums = str(...), but for multi-digit results that's probably not what you want.

Better to just

            nums.append(7)

Or append that getValueAt expression.

CodePudding user response:

Change nums = self.getValueAt(int(i)) to nums.append(self.getValueAt(int(i))). Using = to append items to lists only works if the items you're appending are in a list (edit: or another kind of iterable).

  • Related