To compare multiple variables to a single value

Asked 1 years ago, Updated 1 years ago, 131 views

I'm now creating a function that returns a string of three words by comparing several variables with one integer value. I wonder how to write this in Python. For example,

x = 0
y = 1
z = 3
Mylist = []

if x or y or z == 0 :
    Mylist.append("c")
elif x or y or z == 1 :
    Mylist.append("d")
elif x or y or z == 2 :
    Mylist.append("e")
elif x or y or z == 3 : 
    Mylist.append("f")

This will return the list below.

["c", "d", "f"]

Is this possible?

boolean-logic python if문 match compare

2022-09-22 13:45

1 Answers

You seem to misunderstand how boolean expression works. This is different from the sentence in natural language, and I think you want to compare the same number as below.

if x == 1 or y == 1 or z == 1:

If you follow the example you posted, x and 'y' are evaluated by themselves. (If 0, False and other numbers True)

This can be expressed briefly as follows:

if 1 in (x, y, z):

As shown below:

if 1 in {x, y, z}:

A better way would be to use the set to gain the advantage of eliminating duplicate values.

With or, Python sees each content as a separate syntax. x or y == 1 is divided into the first test for x and the test for y == 1 if it is false.

This is a result of operator priority. Because the or operator has a lower priority than the == operator, it is evaluated earlier.

Of course, even if x or yor z == 1 is interpreted as (x or yor z) == 1, the result will not come out as desired.

Boolean expressions connected by or such as x or y or z are determined as soon as they meet a variable with a true value. Because if only one thing is true, the whole thing is true. In python, 0 or empty (for lists or dictionaries), or false are all interpreted as false. See Boolean expression to find out what value Python is judging as false.

For example, if x = 2; y = 1; z = 0 , the value of the Boolean expression x or y or z becomes 2, the first true value to meet. Therefore, even though y==1 is true, the value of x or z becomes 2, so it becomes 2==1 and becomes false.


2022-09-22 13:45

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.