[Tutor] Having Troubles with For Loops

Corey Richardson kb1pkl at aim.com
Sat Feb 19 19:22:25 CET 2011


On 02/19/2011 01:06 PM, jyatesster wrote:
> I am refreshing my memory of Python programming after taking a class this
> past fall. I am using the book, *Python Programming for the absolute
> beginner*. I am at chapter 4, challenge 4 which instructs me to create a
> program that picks a random word and the player has to guess the word. The
> computer tells the player how mnay letters are in the word. Then the player
> gets five chances to ask if a letter is in the word. The computer can only
> respond with "yes" or "no." Then, the player must guess the word.
> 
> Here is what I have so far. I think I am doing something wrong with the for
> loops as the program is not reading whether the letter is in the constant
> and giving the appropriate response.
>  [snip]

You're going about it wrong. You should look into the len() function.
For example:

print("This word has %d letters" % (len(word)) )
for i in range(5):
    letter = input("Guess a letter: ")
    if letter.lower() in word.lower():
        print("Yes")
    else:
        print("No")

Your for loops in the end don't do what you think they do.

for letter in XYLOPHONES: # Loops through XYLOPHONES
    if letter.lower() not in XYLOPHONES: # Always will return false,
        print("No")    # because you are looping through the word itself
        # etc.

You are also mixing Python 3's print() with Python 2's raw_input(), so
it's hard to tell which you are using. I'm assuming Python 2 because you
didn't report the raw_input() failing. If that's the case, you don't
need the ()'s around the text you are printing.

I also suggest you look into lists and list indexing. You should go
through the Python Tutorial [0] if you haven't before.

[0] - http://docs.python.org/tutorial/
-- 
Corey Richardson

I've never known any trouble which an hour's
reading didn't assuage.
-Charles De Secondat


More information about the Tutor mailing list