Python Arena
Step 4 of 4

Comparing strings

You have compared strings with == and != already. Two strings are equal only when they have exactly the same characters, capital letters and spaces included:

In the Python interpreter
>>> "Python" == "python"
False
>>> "yes" == "yes "
False
>>> "cat" != "dog"
True

Alphabetical order

< and > work on strings too. A string is "less than" another when it comes first in alphabetical order, as in a dictionary:

In the Python interpreter
>>> "apple" < "banana"
True
>>> "cat" > "car"
True
>>> "car" < "cart"
True

Python compares two strings character by character from the start, and the first character that differs decides. "cat" and "car" differ at the third letter, and t comes after r. When one string runs out first, as "car" does next to "cart", the shorter one comes first.

Together with elif, this puts two words in order:

first = input("First word: ")
second = input("Second word: ")
if first < second:
    print(f"{first} comes before {second}")
elif first > second:
    print(f"{second} comes before {first}")
else:
    print("The words are the same")
Input
pear
apple
Output
First word: pear
Second word: apple
apple comes before pear

Capitals and digits

Python's order isn't quite a dictionary's. It compares the codes of the characters, and in them every capital letter comes before every small letter. Letters with marks, such as é, come after all of these. Digits in a string are just characters as well, compared one at a time:

In the Python interpreter
>>> "Zebra" < "apple"
True
>>> "10" < "9"
True
>>> 10 < 9
False

"10" comes before "9" because its first character, 1, comes before 9. So compare words written the same way (all in small letters, for example), and convert numbers that the user typed with int before you compare them.

Your task

Challenge 1 of 3

What does this program print? Type each line it prints.

Challenge 2

In a word-guessing game, the secret word is maple, and the game gives hints by alphabetical order. Write a program that asks for a guess (in small letters). If the guess comes before the secret word, it prints My word comes later., if it comes after it, My word comes earlier., and if it's the secret word, You found it!

Your guess: tiger
My word comes earlier.

Challenge 3

A library shelves its books by the author's last name, in small letters. Names that come before h in alphabetical order go on shelf A, names from h up to (but not including) p on shelf B, and the rest on shelf C. Write a program that asks for the name and prints the shelf.

Author's last name: orwell
Shelf B