I have a function that can return one of three values: a, b, or c.
def f():
return x # a, b, or c
I need to execute different statements based on the return value of f()
: A, B, or C. The best way to do this, that I know of, is:
v = f()
if v == a:
# Do A
elif v == b:
# Do B
else:
# Do C
Without introducing this new variable v
, is there a different way to evaluate the return value of f()
?
Something like this, maybe?
if f() == a:
# Do A
elif _value_from_above == b:
# Do B
else:
# Do C
Probably not what you want, but one option is to use a dictionary of functions:
def do_a();
..
def do_b();
..
def do_c();
..
strategy = {
a: do_a,
b: do_b
c: do_c
}
strategy[f()]()
But normally you'd want some error handling in case the dictionary entry wasn't found, in which case you'd likely end up with a separate variable anyway, plus you now have to extract each case into its own function.
Maybe even less relevant, if there are only two cases you can use a ternary operator:
do_a() if f() == a else do_b()
Though likely you already know this, plus your question has more than two cases, plus lots of people don't like the ternary operator, but anyway.
If you have a language with a switch statement, like C#/Java/C++ etc, or a pattern matching statement, like any of Haskell/OCaml/F#/Scala/Erlang etc, then you can use those. A pattern matching statement looks like this:
match f() with
| a ->
// do something
// and maybe something else too
| b ->
// do some other thing
// and yet some other thing
but there is no such feature in Python.
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