+ 1
Can anyone tell me why the output is Mary
3 Answers
+ 3
After the first iteration, temp will be "Dave" because an empty string " " is "smaller" than the string "Dave" (the strings are compared lexicographically, " " has the ASCII value 32 and 'D' from "Dave" has the ASCII value 68). In the second iteration, "Dave" will be replaced by "Mary" because "Mary" comes after "Dave". The third iteration won't change anything ("John" < "Mary").
+ 4
1. The for loop goes through the keys of the dictonary, not through the values. The keys are "Dave", "Mary" and "John"
2. Strings in Python are compared lexicographically i.e using ASCII value of the characters. So " " < "Dave" < "John" < "Mary"
3. As "Mary" is maximal value it is returned by the code
+ 1
for key in ages:
Here key will assume the values "Dave", "Mary" and finally "John".
if temp < key:
temp = key
In the first pass of "for key in ages" the value of temp is " ".
And the value of key is "Dave".
Because "Dave" > " " temp is now "Dave".
In the second pass it will compare the key "Mary" with temp "Dave".
Since M > D, temp value is now Mary.
In the last pass, John is compared to Mary and since M > J, temp value stills as "Mary".
Hope it is clear. English is not my native language.