Python Forum
Why isnt this word length selector working - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Why isnt this word length selector working (/thread-2575.html)



Why isnt this word length selector working - Ivan - Mar-25-2017

This is the hole program, its a basic hangman game however im just trying to extend it so it has some other functions like choosing your word length. I haven't finished the hole wordLength function so don't focus on that. If possible can someone tell me why there is an IndexError and tell me how to fix it.

import random,sys

Hangman = ['''
   +---+
       |
       |
       |
       |
       |
 =========''','''

   +---+
   |   |
       |
       |
       |
       |
 =========''', '''

   +---+
   |   |
   O   |
       |
       |
       |
 =========''', '''

   +---+
   |   |
   O   |
   |   |
       |
       |
 =========''', '''

   +---+
   |   |
   O   |
  /|   |
       |
       |
 =========''', '''

   +---+
   |   |
   O   |
  /|\  |
       |
       |
 =========''', '''

   +---+
   |   |
   O   |
  /|\  |
  /    |
       |
 =========''', '''

   +---+
   |   |
   O   |
  /|\  |
  / \  |
       |
 =========''']

words = 'ant baboon badger bat bear beaver camel cat clam cobra cougar coyote crow deer dog donkey duck eagle ferret fox frog goat goose hawk lion lizard llama mole monkey moose mouse mule newt otter owl panda parrot pigeon python rabbit ram rat raven rhino salmon seal shark sheep skunk sloth snake spider stork swan tiger toad trout turkey turtle weasel whale wolf wombat zebra'.split()

def GetRandomWord(word):
    chosenWord = random.choice(word)
    return chosenWord

def wordLength(word,wordList):
    userEntury = input("Would you like Tier 1 or Tier 2 words? (1 or 2):")
    if userEntury == '1':
        index = wordList.index(word)
        index=index-1
        if len(word[index]) >= 5:
            return word
        else:
            while True:
                try:
                    index+=1
                    if len(word[index]) >= 5:
                        return word
                except IndexError:
                    newIndex = len(wordList)-1
                    index = newIndex
                    while len(word[index])>5:
                        index +=1
                        if len(word[index]) <= 5:
                            return word
                        
                        
                        
                    
    elif userEntury == '2':
        index = wordList.index(word)
        if index <= 4:
            return word
        else:
            while True:
                index+=1
                word[index]
                if index <= 4:
                    break
                    return word 
    

def display(hangmanPic,secretWord,numWrongLetters,correctLetters):
    blanks = ['-']*len(secretWord) # makes list of strings instead of putting all into one string

    for i in range(len(secretWord)):#repleaces blank letters with correct letters
        if secretWord[i] in correctLetters:
             blanks[i] = secretWord[i] #looks through each string and changes it if needed

    print("Missing Letters:")        
    for letter in blanks:
        print(letter,end='')
    print(hangmanPic[numWrongLetters])
    
    

def getGuess(alreadyGuessed):
    while True:
        print("Guess Letter:")
        guess = input()
        guess = guess.lower()
        if len(guess) != 1:
            print("Please enter only 1 letter.")
        elif guess in alreadyGuessed:
            print("Letter is already guessed.")
        elif guess.isdigit():
            print("Please enter a letter not integer.")
        else:
            return guess
    
def playAgain():
    print("Do you want to play again?(yes or no)") 
    return input().lower().startswith('y')



print("H A N G M A N")

correctLetters = ''
guessedLetters = ''
wrongLetters = 0
randomWord = GetRandomWord(words)
#print(randomWord)
gameDone = False
GameIsRunning = True
WordLength = wordLength(randomWord,words)

while GameIsRunning:
    
    display(Hangman,WordLength,wrongLetters,correctLetters)
    guess = getGuess(correctLetters + guessedLetters)

    if guess in randomWord:
        correctLetters += guess

        #Checks if player has won
        foundAllLetters = True
        for i in range(len(randomWord)):
            if randomWord[i] not in correctLetters:
                foundAllLetters = False
                break
        if randomWord[i] in correctLetters:
            foundAllLetters = True
            print("Well Done You found what the missing word is!")
            gameDone = True
            
    else:
        wrongLetters +=1
        guessedLetters += guess

        #Check if player has lost

        if wrongLetters == len(Hangman)-1:
            print(Hangman[7])
            print("""You have ran out of guesses the word was %s. You had %d correct guess(es) out of %d in total.
                  """ % (randomWord,len(correctLetters),len(Hangman)))
            gameDone = True
            

    #Ask player to play again
    
    if gameDone == True:
        if playAgain():
            wrongLetters = 0
            guessedLetters = ''
            correctLetters = ''
            randomWord = GetRandomWord(words)
            gameDone = False
        else:
            GameIsRunning = False
            exit()



RE: Why isnt this word length selector working - sparkz_alot - Mar-25-2017

Please post the entire Traceback error.


RE: Why isnt this word length selector working - Ivan - Mar-26-2017

(Mar-25-2017, 10:08 PM)sparkz_alot Wrote: Please post the entire Traceback error.

This is the TraceBack error :
Error:
Traceback (most recent call last):   File "C:\Users\Gaming\Desktop\Hangman Extended.py", line 154, in <module>     WordLength = wordLength(randomWord,words)   File "C:\Users\Gaming\Desktop\Hangman Extended.py", line 79, in wordLength     if len(word[index]) >= 5: IndexError: string index out of range
Also When you run the program it will ask you to select a Tier Please Enter 1 not 2

Moderator Larz60+: Changed traceback display to error block


RE: Why isnt this word length selector working - nilamo - Mar-26-2017

Add some print statements to see what's happening. Whatever index is, it's apparently a bigger number than however many items/characters are in word.


RE: Why isnt this word length selector working - Ivan - Mar-26-2017

(Mar-26-2017, 05:46 PM)nilamo Wrote: Add some print statements to see what's happening.  Whatever index is, it's apparently a bigger number than however many items/characters are in word.

Nope doesnt work the List contains 64 elements i think and it says that 'index' is out of range when 'index' is on the 14th element omg ...


RE: Why isnt this word length selector working - nilamo - Mar-26-2017

word isn't a list.


RE: Why isnt this word length selector working - sparkz_alot - Mar-26-2017

Please do not PM members for answers, it defeats the purpose of the forum.

Your code is quite difficult to follow, using to similar variable names, for instance 'word' and 'words'.  Be inventive, instead use something like 'word_list = ', 'random_word = ' and so on.  Also, you don't want to use Python words as variables, for example, 'index' is a list attribute

my_list = [1, 2, 3]
my_list.index(1)    # Will return '0'.  Remember, indexes start with '0', not '1' 
Your problem lies in your while/try/except clause.  So as nilamo suggested, where would be a good place (or places) to put a 'print' to test the value of the variable that puts you there?