June 27, 2018
Test multiple variables against a value in Python
Problem
In this beginner level code snippet, we are going to test multiple variables against a value in Python. Check out the code snippet below
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
# Assume we have the following variables. # We need to check if any variable equals to 1 x = 1 y = 2 z = 3 # One way is to check each variable against # the value using an if statement if x == 1 or y == 1 or z == 1: print("x or y or z is a 1") # Another way to do that is to put the # variables in a tuple or list then # iterate and check if 1 in (x, y, z): print ("x or y or z is a 1") # You can use a set as well if 1 in {x, y , z}: print("x or y or z is a 1") # what if you need to know which variable # matches the value that we are testing. # One suggested way is to use a dictionary dic = {} # Use the variable name as key dic['x'] = 1 dic['y'] = 2 dic['z'] = 3 # Go through keys and values and check for key, val in dic.items(): if val == 1: print("The variable {} has a value of 1".format(key)) |
Thanks for visiting. Please use the comments section below for feedback