Exam4Training

What is the expected output of the following code?

What is the expected output of the following code?

x = True

y = False

z = False

if not x or y:

print(1)

elif not x or not y and z:

print(2)

elif not x or y or not y and x:

print(3)

else:

print(4)
A . 4
B. 3
C. 2
D. 1

Answer: B

Explanation:

Topics: if elif else not and or operator precedence

Try it yourself:

x = True

y = False

z = False

# if not x or y:

# if (not True) or False:

# if False or False:

if False:

print(1)

# elif not x or not y and z:

# elif (not True) or (not False) and False:

# elif False or True and False:

# elif False or (True and False):

# elif False or False:

elif False:

print(2)

# elif not x or y or not y and x:

# elif (not True) or False or (not False) and True:

# elif False or False or True and True:

# elif False or False or (True and True):

# elif False or False or True:

# elif (False or False) or True:

# elif False or True:

elif True:

print(3) # 3

else:

print(4)

There are three operators at work here.

Of them the not operator has the highest precedence, followed by the and operator.

The or operator has the lowest precedence.

Exit mobile version