Python Forum
Why isnt this word length selector working
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Why isnt this word length selector working
#1
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()
Reply
#2
Please post the entire Traceback error.
If it ain't broke, I just haven't gotten to it yet.
OS: Windows 10, openSuse 42.3, freeBSD 11, Raspian "Stretch"
Python 3.6.5, IDE: PyCharm 2018 Community Edition
Reply
#3
(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
Reply
#4
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.
Reply
#5
(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 ...
Reply
#6
word isn't a list.
Reply
#7
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?
If it ain't broke, I just haven't gotten to it yet.
OS: Windows 10, openSuse 42.3, freeBSD 11, Raspian "Stretch"
Python 3.6.5, IDE: PyCharm 2018 Community Edition
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Working with Excel and Word, Several Questions Regarding Find and Replace Brandon_Pickert 4 1,492 Feb-11-2023, 03:59 PM
Last Post: Brandon_Pickert
Question Problem: Check if a list contains a word and then continue with the next word Mangono 2 2,455 Aug-12-2021, 04:25 PM
Last Post: palladium
  Looping if condition isnt met finndude 6 2,855 May-03-2021, 08:01 PM
Last Post: Skaperen
  Python Speech recognition, word by word AceScottie 6 15,860 Apr-12-2020, 09:50 AM
Last Post: vinayakdhage
  print a word after specific word search evilcode1 8 4,721 Oct-22-2019, 08:08 AM
Last Post: newbieAuggie2019
  for some reason this isnt working lokchi2017 3 2,658 Aug-06-2018, 12:24 PM
Last Post: perfringo
  average word length syn09001 6 12,428 Jul-18-2018, 08:26 PM
Last Post: micseydel
  difference between word: and word[:] in for loop zowhair 2 3,626 Mar-03-2018, 07:24 AM
Last Post: zowhair
  ISO working example of opening a Microsoft Word document through PyWin32 Orthoducks 1 4,569 Dec-25-2016, 10:12 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020