Computer Science

Predict the output:

d = dict()
d['left'] = '<'
d['right'] = '>'
d['end'] = ' '
print(d['left'] and d['right'] or d['right'] and d['left'])
print(d['left'] and d['right'] or d['right'] and d['left'] and d['end']) 
print((d['left'] and d['right'] or d['right'] and d['left']) and d['end']) 
print("end")

Python Dictionaries

5 Likes

Answer

Output
>
>

end
Explanation
  1. print(d['left'] and d['right'] or d['right'] and d['left'])
    1. and operator has higher precedence than or so d['left'] and d['right'] and d['right'] and d['left']) will be evaluated first.
    2. d['left'] and d['right'] will return value of d['right'] i.e. '>' because first operand of and operator is true so it will return the value of second operand.
    3. Similarly, d['right'] and d['left']) will return value of d['left'] i.e. '<'.
    4. Now the expression becomes '>' or '<'. This expression will evaluate to '>' as or operator returns its first operand if the first operand is true. (or operator returns its second operand only when its first operand is false). Thus, '>' gets printed as the first line of the output.
  2. print(d['left'] and d['right'] or d['right'] and d['left'] and d['end'])
    1. and operator has higher precedence than or so d['left'] and d['right'] and d['right'] and d['left'] and d['end'] will be evaluated first.
    2. d['left'] and d['right'] will return value of d['right'] i.e. '>'.
    3. d['right'] and d['left'] will return value of d['left'] i.e. '<'. d['right'] and d['left'] and d['end'] becomes '<' and ' '. and operator returns its second operand in this case so the expression evaluates to ' '.
    4. Now the expression becomes '>' or ' '. or operator will return first operand in this case. Thus, '>' gets printed as the second line of the output.
  3. print((d['left'] and d['right'] or d['right'] and d['left']) and d['end'])
    1. (d['left'] and d['right'] or d['right'] and d['left']) will be evaluated first as it is enclosed in parentheses. From part 1, we know this expression will return '>'.
    2. Now the expression becomes '>' and d['end'] i.e., '>' and ' '. and operator returns ' ', its second argument as its first argument is true. Thus, ' ' gets printed as the third line of the output.

Answered By

2 Likes


Related Questions