[Tutor] Hangman game.....problem putting strings in a list.....

Alan Gauld alan.gauld at btinternet.com
Tue Dec 21 11:21:14 CET 2010


"Yasin Yaqoobi" <yasinyaqoobi at gmail.com> wrote

I'm confused. The error message you describe doesn't
appear to match any line in your code.

Please provide the full error printout not just a single line.
Meanwhile some comments...

> global line
> global index;

global is not doing anything here, it is only effective inside a 
function.

Try not to use global variables unless you have to. Specifically only
for data that's shared between functions, and even then it's usually
better practice to pass the values into the functions as arghuments.

> guessed = ["-"];
> count = 0;
> wrong = 0;
>
> def guess(letter):
>     global guessed

>     if (letter in line):

You don't need the parens, they don't do any harm,
but they aren't needed.

>         index = line.index(letter);
>         print guessed;

> # This is the line that gives me the error don't know why? 
> guessed[index] = " " + (letter); ,TypeError: 'str' object does not 
> support item assignment

>         guessed[index] = (letter);

Again, you don't need the parens...
And I suspect you really want to use append() here rather
than assigning to guessed[index].

>         print ' '.join(guessed)
>     else:
>         global wrong;
>         wrong += 1;
>
>
> def draw(number):...

> def doit():
>     global count
>     while(wrong != 7):
>         a_letter = raw_input("Pick a letter --> ")
>         print
>         guess(a_letter);
>         draw(wrong);
>         print
>         count += 1
>
> def initArray():
>     global guessed
>     print line
>     guessed =  guessed[0] * (len(line)-1)
>     print "this is new list " + guessed;

If you use the append() method you don't need this.

> while 1:
>     line = file.readline();
>     if (len(line) >= 5):
>         initArray()
>         doit();
>         break
>     if not line: break
>
> file.close()

HTH,


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




More information about the Tutor mailing list