Search code examples
pythoncomparisonvariable-assignmentlogical-operators

Multiple comparison operators on a single line


I'm taking an intro to python course, and there was one question on a quiz that I could not make heads or tails of. Given this code, the question asks what value will be assigned to x:

z = 2
y = 1
x = y < z or z > y and y > z or z < y

I'm really confused about where the assignment is in this statement. Should I read this as "x equals y if y is less than z"? I can't even begin to understand how to read "or" and "and" in this context.

Thanks in advance.


Solution

  • you have to read it like this, x will be a boolean (true or false) and so will each of the comparison expressions

    z = 2
    y = 1
    
    x = y < z or z > y and y > z or z < y
    
    x = ( (y<z) or ((z>y) and (y>z)) or (z<y) )
    x = ( True or (True and False) or False )
    x = True