chanwcom
chanwcom

Reputation: 4680

Using the while loop in Python to retrieve and check the value at the same time

When I program using the C++ language, I use the following while loop pattern quite often.

while ((Data data = GetNewData()) != END) {
  // Do some processing
  ProcessData(data);
}

How can we do the same thing in Python? It seems like the following doesn't work.

while (data = GetNewData()) != END:
  # Do some processing
  ProcessData(data)

Then one alternative I can think of is the following.

while 1:
  data = GetNewData()
  if data == END:
    break
  # Do some processing using data
  ProcessData(data)

But the above doesn't look neat. Could anyone suggest a good way?

Upvotes: 2

Views: 87

Answers (1)

yinnonsanders
yinnonsanders

Reputation: 1871

In Python, assignment is a statement, not an expression, which is why

while (data = GetNewData()) != END:
    # Do some processing
    ProcessData(data)

doesn't work. (data = GetNewData()) cannot be used as a value.

Instead, you could use iter:

for data in iter(GetNewData, END):
    # Do some processing
    ProcessData(data)

The loop will call GetNewData() each iteration, and assign the value to data unless it is equal to END. While this syntax is definitely not as intuitive as the C++ way, it does eliminate bugs where = is substituted for == and vice versa.

Upvotes: 2

Related Questions