10
Question Question 9(b)
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")Output
>
>
end
Explanation
print(d['left'] and d['right'] or d['right'] and d['left'])andoperator has higher precedence thanorsod['left'] and d['right']andd['right'] and d['left'])will be evaluated first.d['left'] and d['right']will return value of d['right'] i.e.'>'because first operand ofandoperator is true so it will return the value of second operand.- Similarly,
d['right'] and d['left'])will return value of d['left'] i.e.'<'. - 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.
print(d['left'] and d['right'] or d['right'] and d['left'] and d['end'])andoperator has higher precedence thanorsod['left'] and d['right']andd['right'] and d['left'] and d['end']will be evaluated first.d['left'] and d['right']will return value of d['right'] i.e.'>'.d['right'] and d['left']will return value of d['left'] i.e.'<'.d['right'] and d['left'] and d['end']becomes'<' and ' '.andoperator returns its second operand in this case so the expression evaluates to' '.- Now the expression becomes
'>' or ' '.oroperator will return first operand in this case. Thus,'>'gets printed as the second line of the output.
print((d['left'] and d['right'] or d['right'] and d['left']) and d['end'])(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'>'.- Now the expression becomes
'>' and d['end']i.e.,'>' and ' '.andoperator returns' ', its second argument as its first argument is true. Thus,' 'gets printed as the third line of the output.