Home > other >  How to use the result of a function call as condition of the loop and in the body of the loop?
How to use the result of a function call as condition of the loop and in the body of the loop?

Time:09-28

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.

CodePudding user response:

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
  • Related