What's printed by the following Pyhon code?
Question:
animals = ['horse', 'Pig', 'dog', 'Owl', 'lion', 'Hare', 'baboon', 'Fish', 'tiger', 'Zebra', 'Cow', 'Mouse', 'quail', 'Elephant']
for animal in animals:
if (animal >= 'M') and (animal <= 'Z'):
print(animal)
Question 1:
How to understand (animal >= 'M') and (animal <= 'Z')
?
Question 2:
The correct answer is Pig
Owl
Mouse
, why Zebra
is not printed in this case?
Answers:
Like zvone pointed out, string are compared alphabetically and therefor Zebra is not printed.
The alphabetic order in this case would be.
X
Y
Z
Za
Zebra
- Animals that come alphabetically between “M” and “Z”.
- “Zebra” comes after “Z” when sorted in python.
from a to z ordering is like that in alpha characters:
["a","aa","aaa" … "ab","aba","abaa" … "b"… "z", "za", "zaa" …
"zebra" … "zzzzz" …]
depending on their string representation of ascii equvalent is a < b < c … < y < z and z always comes before z* (asterix means any)
-
it will print animals that start from letters between ‘M’ and ‘Y’ (both included) and also single letter "Z".
-
because "Z" < "Zebra"
animals = ['horse', 'Pig', 'dog', 'Owl', 'lion', 'Hare', 'baboon', 'Fish', 'tiger', 'Zebra', 'Cow', 'Mouse', 'quail', 'Elephant']
for animal in animals:
if (animal >= 'M') and (animal <= 'Z'):
print(animal)
Question 1:
How to understand (animal >= 'M') and (animal <= 'Z')
?
Question 2:
The correct answer is Pig
Owl
Mouse
, why Zebra
is not printed in this case?
Like zvone pointed out, string are compared alphabetically and therefor Zebra is not printed.
The alphabetic order in this case would be.
X
Y
Z
Za
Zebra
- Animals that come alphabetically between “M” and “Z”.
- “Zebra” comes after “Z” when sorted in python.
from a to z ordering is like that in alpha characters:
["a","aa","aaa" … "ab","aba","abaa" … "b"… "z", "za", "zaa" …
"zebra" … "zzzzz" …]
depending on their string representation of ascii equvalent is a < b < c … < y < z and z always comes before z* (asterix means any)
-
it will print animals that start from letters between ‘M’ and ‘Y’ (both included) and also single letter "Z".
-
because "Z" < "Zebra"