The problem I am working on is explained below:
2.1) Write a program that asks a user to input a color.
If the color is black or white, output “The color was black or white”.
If it starts with a letter that comes after “k” in the alphabet,
output “The color starts with a letter that comes after “k” in the
alphabet”. (Optional: consider both capitalized and non-capitalized
words. Note: the order of the alphabet in Unix and Python
is: symbols, numbers, upper case letters, lower case letters.)
Here is the authors solution:
#!/usr/bin/env python
#
# guess a color
#
answer = raw_input ("Please enter a color: ")
if (answer == "black") or (answer == "white"):
print "The color was black or white."
elif answer >= "k":
print "The color starts with a letter that comes after \"k\" in the alphabet."
This is my answer to the problem:
#!usr/bin/env python
#
#This program asks the user to input a color
color = raw_input("Please, enter a color, any color.")
if (color == "black") or (color == "white"):
print "The color was black or white."
elif color[0] != "a" or "b" or "c" or "d" or "e" or "f" or "g" or "h" or "i" or "j" or "k":
print "The color starts with a letter that comes after 'k' in the alphabet."
else:
print "The color was niether black nor white."
I am having trouble understanding how the authors solution works, specifically for identifying if, “The color starts with a letter that comes after “k” in the alphabet”.
How is does Python make this work?
elif answer >= "k":
How is Python identifying the first character, such as color[0] and the range of letters beyond k?
Because in general, Python sequences (strings included) implement lexicographical ordering for their elements. So first element 0 is compared, if the same then element 1, etc.
Note, though, that your solution is wrong. It’s parsed as
(color[0] != "a") or "b" or "c" or "d" or "e" or "f" or "g" or "h" or "i" or "j" or "k", which is false only whencolor[0] == 'a'. You’re looking forcolor[0] not in ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j')(you shouldn’t exclude ‘k’, either), but using>=is just a much, much cleaner thing to do.