Syntax Error in my Even class

Question:
Does anyone know why i am getting a syntax error in the if statement underneath the next function?
Repl link:
https://replit.com/@jonathanessombe/learn-1#main.py

class Even:
  def __init__(self, initial,max):
    self.initial = initial
    self.max = max

  def __iter__(self):
    return self

  def __next__(self):
    if self.initial <= self.max:
      return  self.initial = self.initial + 2
    else:
      print('You have reached the maximum value in this iterator. You cannot iterate any further')


even_numbers = Even(2, 14)
print(next(even_numbers))
print(next(even_numbers))

You should use the return statement to return the next even number, and then update the self.initial value outside of the return statement.

try this:

class Even:
    def __init__(self, initial, max):
        self.initial = initial
        self.max = max

    def __iter__(self):
        return self

    def __next__(self):
        if self.initial <= self.max:
            result = self.initial  # Store the current value
            self.initial += 2     # Update the value for the next iteration
            return result
        else:
            raise StopIteration("You have reached the maximum value in this iterator. You cannot iterate any further")

even_numbers = Even(2, 14)
print(next(even_numbers))
print(next(even_numbers))
1 Like

you can’t return an expression using the return statement?

a return statement is used to return a value, but in your case you used it for assignment → =

2 Likes

That sounds like a use for the walrus operator (:=):

        if self.initial <= self.max:
            return (self.initial := self.initial+2)
2 Likes

No, you can’t use a walrus operator for attribute assignment. It will raise a SyntaxError.
Also, I think the original self.initial is supposed to be returned, not the updated number.

1 Like
class Even:

  iter_count = 0
  next_count = 0
  
  def __init__(self, initial,max):
    self.initial = initial
    self.max = max

  def __iter__(self):
    self.iter_count += 1
    return self

  def __next__(self):
    if self.iter_count >= 1:
      if self.next_count == 0:
        self.next_count += 1 
        return self.initial
      elif (self.initial+2) > self.max:
        return 'You have reached the maximum value in this iterator. You cannot iterate any further'
      if self.next_count > 0:
        self.initial = self.initial + 2
        return  self.initial
    else:
      return 'Use the iter function first before using the next function'

even_numbers = Even(0, 10)
iter(even_numbers)
print(next(even_numbers))
print(next(even_numbers))
print(next(even_numbers))
print(next(even_numbers))
print(next(even_numbers))
print(next(even_numbers))
print(next(even_numbers))

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.