Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading