So I have a lot of variables(int) and want to add a number to all of it at once because i need it for a statement
here an example:
a, b, c, d = 3,5,6,7
if a i == 10 or b i == 10 or c i == 10 or d i == 10:
#do something
Is there anyway i can compact this if statement
CodePudding user response:
You can use any
(for python doc, see https://docs.python.org/3/library/functions.html#any) with generator comprehension:
a, b, c, d = 3,5,6,7
i = 3
if any(x i == 10 for x in (a, b, c, d)):
print('hello')
Unless necessary, I would prefer to have the numbers in a single list, not in seperate variables.
nums = [3, 5, 6, 7]
i = 3
if any(x i == 10 for x in nums):
print('hello')
CodePudding user response:
Since you have a common denominator i
that all if conditions share - why not calculate that subtracted value outside the if condition instead?
a, b, c, d = 3,5,6,7
j = 10 - i
if a == j or b == j or c == j or d == j:
#do something
CodePudding user response:
You could put all the numbers into a list or array and loop through a forloop to check, this would be helpful if you have a lot of numbers but with only 4 its not all that big of a deal