0

The following concept works in the C and C++ languages, you assign the result of a function to a variable and then use the newly assigned variable as the condition for the while loop. So using the comma operator.

A sample bit of C++ code looks like this. I've mocked the behavior of a function call by doing an assignment from an array. In my real situation the function only provides the value once and I want to use it as the condition but also in the while body loop. There isn't another end condition available to me.

#include <iostream>

int main(){
    int vals[] = {1, 2, 3, 4};

    int var = 0;
    int i=0;
    while(var = vals[i], var != 3){ // vals mocks the function
        std::cout << var << std::endl; // mock usage of value stored in var
        i++;
    }
}

What would be a pythonic way to take the results of my function call, use it as a conditional in my loop and use it in my loop body? In other languages the do-while loop could solve this problem but python doesn't have it.

Tarick Welling
  • 3,119
  • 3
  • 19
  • 44
  • @Vlad, super! Also nice that the name of the operator is a better (searchable) one than just 'comma'. – Tarick Welling Sep 27 '22 at 14:19
  • Does this answer your question? [One line if-condition-assignment](https://stackoverflow.com/questions/7872838/one-line-if-condition-assignment) or [Assign within if statement Python](https://stackoverflow.com/questions/30066516/assign-within-if-statement-python) – Abdul Aziz Barkat Sep 27 '22 at 14:23

1 Answers1

1

The so-called "walrus operator" (introduced in 3.8) is ideal for this.

Here's an example:

def func():
    return 1 # obviously not a constant

while (n := func()) != 0:
    print(n) # infinite loop in this example but you get the point
DarkKnight
  • 19,739
  • 3
  • 6
  • 22