I am using Python and I would like to have an if statement with many variables in it.
Such as:
if A, B, C, and D >= 2: print (A, B, C, and D)
I realize that this is not the correct syntax and that is exactly the question I am asking — what is the correct Python syntax for this type of an if
statement?
To check if a variable is equal to all of multiple values, use the logical AND (&&) operator to chain multiple equality comparisons. If all comparisons return true , all values are equal to the variable. Copied! We used the logical AND (&&) operator to chain multiple equality checks.
(a==b) will be compared first and return either 1 (true) or 0 (false). Then value of variable c will be compared with the result of (a==b).
To test multiple variables x , y , z against a value in Python, use the expression value in {x, y, z} . Checking membership in a set has constant runtime complexity. Thus, this is the most efficient way to test multiple variables against a value.
Python chains such relational operators naturally (including in and is ). a() == b() == c() is functionally equivalent to a() == b() and b() == c() whenever consecutive calls to b return the same value and have the same aggregate side effects as a single call to b .
You want to test a condition for all
the variables:
if all(x >= 2 for x in (A, B, C, D)): print(A, B, C, D)
This should be helpful if you're testing a long list of variables with the same condition.
If you needed to check:
if A, B, C, or D >= 2:
Then you want to test a condition for any
of the variables:
if any(x >= 2 for x in (A, B, C, D)): print(A, B, C, D)
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