Home > Net >  Does Python have the C equavalent of (var = value, var)
Does Python have the C equavalent of (var = value, var)

Time:07-22

In C (and maybe C), you are able to do the following:

uint8_t one = 0;

if ((one = randomUint8t(), one) == 255){
 printf("One has the max uint8_t value");
}

So you assign the value of the random uint8 function to one, and you return one to be used in the expression evaluation.

This particularly useful if you are trying to debug a while loop or if you want to assign a value to a variable unconditionally, but enter the if statement (or not) based on the new value of that same variable.

CodePudding user response:

This is possible since Python 3.8 with assignment expressions aka the "walrus" operator :=. Example:

import random

if (one := random.randint(0, 255)) == 255:
    print("one == 255")
  • Related