I have a Python function which returns a tuple with a boolean and string
def check_something():
# ...
return bool_value, str_messsage
Is there a way I can use the output of this function in an if statement using the boolean and assign the string value to a variable in the if statement
if not check_something():
# ...
if (result := check_something())[0]:
var = result[1]
This uses the 'walrus operator', which is new syntax that was introduced in Python 3.8. You can read about it here.
For Python <= 3.7, you have to include one extra line:
bool_val, str_message = check_something()
if bool_val:
var = str_message
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With