Reputation: 117
I am a GCSE Computing student who is relatively new to python. I am on my third programming task which involves making a simple hangman game. I have managed to get the game working but part of the success criteria is that the user can change the set of words. At the minute the program is using a list of preset words. I have managed to write the code allowing the user to enter the new sets of words in and these are then stored as a list. However I have had problems when trying to replace the old set of words with the new list entered by the user. I am incredibly stuck and as I am still on holiday have been unable to ask my teacher for help. Any help or suggestions would be greatly appreciated as I am running out of time (we are taking the GCSE in June 2013) Thanks.
def newwords():
newgamewords.append(input('Enter new word: '))
print('Do you want to add any more words? yes or no?')
answer=input()
if answer == 'yes':
newwords()
else:
while len(guessedletters) > 0 : guessedletters.pop()
while len(displayletters) > 0 : displayletters.pop()
while len(hangmanpics) > 0 : hangmanpics.pop()
gamewords[:]=newgamewords
hangmangame()
Here is some of the code...
Upvotes: 1
Views: 257
Reputation: 309949
You can replace the elements in a list (in place) using slice assignment:
word_list = [ 'foo','bar','baz' ]
new_list = [ 'qux','tux','lux', 'holy cow! python is awesome' ]
word_list[:] = new_list
print(word_list) #[ 'qux','tux','lux', 'holy cow! python is awesome' ]
new_list
and old_list
don't even need to be the same length.
You can also replace only part of a list with part of the other list if you'd like:
word_list = [ 'foo','bar','baz' ]
new_list = [ 'qux','tux','lux', 'holy cow! python is awesome' ]
word_list[1:-2] = new_list[:-1]
print word_list #['foo', 'qux', 'tux', 'lux', 'bar', 'baz']
Upvotes: 2