How do I check against the first 7 elements of the list in order to print some text?

Issue

From an array, I am trying to use an if statement with 3 conditions – if the chosen word from the ‘wordlist’ list has not yet been guessed correctly and over 7 attempts have been made, I wish to print some hint text. For an unknown reason the hint text always shows on the 7th attempt regardless of which index the chosen word is.

# Create a list of hangman words
  wordList = ["cat","dog","mouse", "giraffe", "otter", "shark", "sheep", "car", "motorbike",
  "bus", "aeroplane", "pizza", "chips", "cheese"]

# Choose a word from the list at random
  wordChosen = random.choice(wordList)

# Keep asking the player until all letters are guessed
  while display != wordChosen:
    guess = input(str("Please enter a guess for the {} ".format(len(display)) + "letter word: "))#[0]
    guess = guess.lower()
    #Add the players guess to the list of used letters
    used.extend(guess)
    print ("Attempts: ")
    print (attempts)

    print(wordChosen) # Added for testing

    # Provide a hint if unsuccessful after 7 attempts
    if attempts >= 7 and guess != wordChosen and wordChosen[0:6]:
      print("HINT: It's an animal")

In this instance, I only want the indexes 0:7 to result in this text. Example, if ‘car’ is chosen from the random function, the text still shows which I do not want.

I tried using numpy however it seem to get closer to the solution by using the following:

# Provide a hint if unsuccessful after 7 attempts
        if attempts >= 7 and guess != wordChosen and wordChosen[0:6]:
          print("HINT: It's an animal")

Solution

You don’t reference wordList in the second to last line to compare:

# Create a list of hangman words
  wordList = ["cat","dog","mouse", "giraffe", "otter", "shark", "sheep", "car", "motorbike",
  "bus", "aeroplane", "pizza", "chips", "cheese"]

# Choose a word from the list at random
  wordChosen = random.choice(wordList)

# Keep asking the player until all letters are guessed
  while display != wordChosen:
    guess = input(str("Please enter a guess for the {} ".format(len(display)) + "letter word: "))#[0]
    guess = guess.lower()
    #Add the players guess to the list of used letters
    used.extend(guess)
    print ("Attempts: ")
    print (attempts)

    print(wordChosen) # Added for testing

    # Provide a hint if unsuccessful after 7 attempts
    if attempts >= 7 and guess != wordChosen and wordChosen in wordList[0:6]:
      print("HINT: It's an animal")

Instead of:

if attempts >= 7 and guess != wordChosen and wordChosen[0:6]:

You need:

if attempts >= 7 and guess != wordChosen and wordChosen in wordList[0:6]:

Answered By – Eli Harold

Answer Checked By – Terry (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.