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")
Answer
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.
Related Questions
What will be the output produced by following code ?
d1 = { 5 : "number", "a" : "string", (1, 2): "tuple" } print("Dictionary contents") for x in d1.keys(): # Iterate on a key list print (x, ':' , d1[x], end = ' ') print (d1[x] * 3) print ( )Predict the output:
d = dict() d['left'] = '<' d['right'] = '>' print('{left} and {right} or {right} and {left}')Predict the output:
text = "abracadabraaabbccrr" counts = {} ct = 0 lst = [] for word in text: if word not in lst: lst.append(word) counts[word] = 0 ct = ct + 1 counts[word] = counts[word] + 1 print(counts) print(lst)Predict the output:
list1 = [2, 3, 3, 2, 5,3, 2, 5, 1,1] counts = {} ct = 0 lst = [] for num in list1: if num not in lst: lst.append(num) counts[num] = 0 ct = ct+1 counts[num] = counts[num]+1 print(counts) for key in counts.keys(): counts[key] = key * counts[key] print(counts)