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?

Asked By: Leo

||

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

Answered By: Peter van Luik
  1. Animals that come alphabetically between “M” and “Z”.
  2. “Zebra” comes after “Z” when sorted in python.
Answered By: Ben

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)

Answered By: obayhan
  1. it will print animals that start from letters between ‘M’ and ‘Y’ (both included) and also single letter "Z".

  2. because "Z" < "Zebra"

Answered By: Savej Hasan