[Tutor] Having Troubles with For Loops

Alan Gauld alan.gauld at btinternet.com
Sat Feb 19 20:15:58 CET 2011


"jyatesster" <jyatesster at gmail.com> wrote

> 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.

Instead of having us guess it would be useful if you told us
(or better cut n paste) what actually happened and why you
thought it was wrong. Besides helping us understand putting
it in words will often help you to understand to the point of
seeing the solution...

> #Word Randomizer
> import random
> # create a sequence of words to choose from
> PYTHON = "python"
> JUMBLES = "jumbles"
> EASY = "easy"
> DIFFICULT = "difficult"
> XYLOPHONES = "xylophones"
> WORDS = (PYTHON, JUMBLES, EASY, DIFFICULT, XYLOPHONES)

Its easier to ,miss out the constants and just do

words = ('python', 'jumbles',....)

> word = random.choice(WORDS)
> # create a variable to use later to see if the guess is correct
> correct = word

You shouldn't need correct since you aren't changing word,
so just use word directly.


> #intial values
> tries = 1
> max_tries = 5

You don't really need these either, see below...

>
> #The computer picks the word and gives a hint

The comment is misleading since the computer picked
the word further up. Move the random function to here...


> if correct == PYTHON:
>    print ("This word has six letters.")
> elif correct == JUMBLES:
>    print ("This word has seven letters.")

You can use len(word) to get the letters without all
the repetition.

print "This word has", len(word), "letters"

> guess_letter = raw_input("Guess a letter: ")

> #The player gets five chances to see if a letter is in the word.
> for letter in PYTHON:
>    if letter.lower() not in PYTHON:

You need to use guess_letter not letter.
letter will be each of the letters in 'python'...

But you don't really want to test the guesses
against python (unless python is the word).
Better to just use word, and you don't need a loop
over the letters you need a loop that repeats up
5 times:

for try in range(5):


>        print ("No")
>        guess_letter = raw_input("Guess a letter: ")

and then use 'in' to find out if the guess_letter is in the word


>        guess_word = raw_input("Guess the word: ")

And you never check to see if the guessed word is the word!.

So the user never actually wins or loses...

You are heading in the right general direction but
you are making it much more complex than it needs
to be.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/




More information about the Tutor mailing list