Search code examples
pythonfunctionif-statementwhile-loop

A random word generator that has the user type the word to confirm


Source code for a random word generator that has the user type the word to confirm

def word_list(): 
  import random #Import random function
  words = ['hello',"yes","no","I","look","where","can","he","with","see","do","we","a","you","play","am","what","one","the","this","have","on","want","go","like","and","hurt","to","under","day","is","or","of","it","are","said","big","up","that","little","down","there","my","she","out","good","her","all","yes","make","read","no","they","your\n"]
  question = random.choice(list(words)) #Generates a random word from the list
  print(question) #Displays the word that was generated
  answer = input('Retype the word and press enter:') #User retypes the 
  while True: #Loop that allows user to 
    if answer == question: #If statement that confirms the user spelled the word right
      print('Great job you spelled it correctly!')
      input('Press enter for another word')
    else: 
      while answer != question:
        print('You spelled that word wrong, please try again!')
        answer = input('Retype the word and press enter:')

Solution

  • You were on the right track, but as @guidot was saying you have to exit that loop, and you need a second loop to keep playing.
    I would've written the code something like this:

    def word_list(): 
        import random #Import random function
        words = ['hello',"yes","no","I","look","where","can","he","with","see","do","we","a","you","play","am","what","one","the","this","have","on","want","go","like","and","hurt","to","under","day","is","or","of","it","are","said","big","up","that","little","down","there","my","she","out","good","her","all","yes","make","read","no","they","your"]
        play = True
        # a first loop for the game, as it seemed that you wanted it "infinte"
        while play:
            # here starts a round, get a word
            question = random.choice(words) #Generates a random word from the list
            print(question) #Displays the word that was generated
            while True: # loop until the player types the word correctly
                answer = input('Retype the word and press enter: ') #User retypes the 
                if answer == question:
                    # the player has answered correctly, award him
                    print('Great job you spelled it correctly!')
                    # check if the player wants to keep playing
                    answer = input('Press enter for another word, write "exit" to stop: ')
                    # if the answer was not exit, keep playing 
                    play = answer.strip() != "exit"
                    # this exit this loop, so it will end the round
                    break
                else:
                    # the answer was wrong 
                    print('You spelled that word wrong, please try again!')