FIRST, A CORRECTION TO THE OR
CONDITIONAL:
You need to say:
if x == 0 or y == 0 or z == 0:
The reason is that "or" splits up the condition into separate logical parts. The way your original statement was written, those parts were:
x
y
z == 0 // or 1, 2, 3 depending on the if statement
The last part was fine --- checking to see if z == 0, for instance --- but the first two parts just said essentially if x
and if y
. Since integers always evaluate to True
unless they're 0, that means the first part of your condition was always True
when x
or y
didn't equal 0 (which in the case of y was always, since you had y = 1
, causing your whole condition (because of how OR
works) to always be True
.
To avoid that, you need to make sure all parts of your condition (each side of the OR
) make sense on their own (you can do that by pretending that the other side(s) of the OR
statement doesn't exist). That's how you can confirm whether or not your OR
condition is correctly defined.
You would write the statements individually like so:
if x == 0
if y == 0
if z == 0
which means the correct mergin with the OR
keyword would be:
if x == 0 or y == 0 or z == 0
SECOND, HOW TO SOLVE THE PROBLEM:
You're basically wanting to check to see if any of the variables match a given integer and if so, assign it a letter that matches it in a one-to-one mapping. You want to do that for a certain list of integers so that the output is a list of letters. You'd do that like this:
def func(x, y, z):
result = []
for integer, letter in zip([0, 1, 2, 3], ['c', 'd', 'e', 'f']):
if x == integer or y == integer or z == integer:
result.append(letter)
return result
Similarly, you could use LIST COMPREHENSION to achieve the same result faster:
def func(x, y, z):
return [
letter
for integer, letter in zip([0, 1, 2, 3], ['c', 'd', 'e', 'f'])
if x == integer or y == integer or z == integer
]
1
in (tuple) – Plattany
/all
functions. For example:all([1, 2, 3, 4, False])
will return Falseall([True, 1, 2, 3])
will return Trueany([False, 0, 0, False])
will return Falseany([False, 0, True, False])
will return True – Huskyif x == 0 or 1:
, which is of course similar toif x or y == 0:
, but might be a little confusing for newbies nonetheless. Given the sheer volume of "Why isn't myx == 0 or 1
working?" questions, I would much rather use this question as our canonical duplicate target for these questions. – Chester0
,0.0
orFalse
. You can easily write wrong code which gives the "right" answer. – Prepossession