I'm learning Python and decided to upgrade a version of the hangman game that was used as an example in one of the courses I watched, the code turned out like this:
import random
word_dictionary = {
1: "mouse",
2: "house",
3: "show",
4: "see",
5: "leave",
6: "shower",
7: "showcase",
8: "coding",
9: "elephant",
10: "apartment",
}
random_number = random.randint(1, 10)
random_word = word_dictionary[random_number]
secret_word = random_word
word_len = len(secret_word)
guess = None
tip = 0
tip_num = None
tip_previous = None
tip_position = None
tip_model_formula = "_"*word_len
tip_model_list = list(tip_model_formula)
send_tip = None
print("Word has", word_len, " letters")
while guess != secret_word:
guess = input("Enter your guess: ")
if guess != secret_word:
print("Wrong answer! Try again!")
tip += 1
if tip == 5:
tip_num = random.randint(0, word_len)
tip_position = secret_word[tip_num]
tip_model_list[tip_num] = tip_position
send_tip = "".join(tip_model_list)
tip_previous = tip_num
print("here's a tip:\n" + send_tip)
if tip == 10:
tip_num = random.randint(0, word_len)
while tip_num == tip_previous:
tip_num = random.randint(0, word_len)
tip_position = secret_word[tip_num]
tip_model_list[tip_num] = tip_position
send_tip = "".join(tip_model_list)
tip_previous = tip_num
print("here's a tip:\n" + send_tip)
if tip == 15:
tip_num = random.randint(0, word_len)
while tip_num == tip_previous:
tip_num = random.randint(0, word_len)
tip_position = secret_word[tip_num]
tip_model_list[tip_num] = tip_position
send_tip = "".join(tip_model_list)
tip_previous = tip_num
print("here's a tip:\n" + send_tip)
if tip == 16:
print("You lost!")
exit()
print("You win!")
(What this does is pick a random word from the dictionary to be the secret word and have the player take guesses on it, every 5 attempts, the player gets 1 tip, which is one letter of the word, after 16 attempts, you lose and have to restart).
When I run it, sometimes it runs as expected, but sometimes it exits with the following error:
Traceback (most recent call last):
File "E:\Program Files\PyCharm Community Edition 2020.2\plugins\python-ce\helpers\pydev\pydevd.py", line 1448, in _exec
pydev_imports.execfile(file, globals, locals) # execute the script
File "E:\Program Files\PyCharm Community Edition 2020.2\plugins\python-ce\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "C:/Users/rafae/PycharmProjects/Beginning/Beg.py", line 55, in <module>
tip_position = secret_word[tip_num]
IndexError: string index out of range
I have no idea why this randomly happens and have been trying to figure out for an hour without success. Thanks for any help in advance.
Your bug is here:
tip_num = random.randint(0, word_len)
tip_position = secret_word[tip_num]
randint
returns a number between its first and second arguments inclusive of both. That means that it can return a result of word_len
, which is one past the end of secret_word
.