How do I get python to pick a random word? Do I have to link it with a dictionary? If so how do you do that.
Exercise from Python Programming for the absolute beginner
Create a game where computer picks a random word and player has to guess the word. Computer tells the player how many letter are in the word. The computer can only respond yes or no. Then the player must guess the word.

Recommended Answers

All 17 Replies

This is not very hard if you use the random module.

import random

words = ['hello','python','monday','tuesday','friday','ice']
choice = random.choice(words)

print "Guess the word!"
guess = raw_input()
while guess.lower() != choice:
    print "sorry, not correct"
    guess = raw_input()
print "well dont that was it!"

But aren't you limiting to those list of words - hello, python, monday, tuesday, friday, and ice. How do you do for like a dictionary amount of words is it even possible?

Here is a random word generator for this dictionary file

from os.path import getsize
from random import randint

dic_path ="DictionaryE.txt"
file_size =getsize (dic_path )
file_in =open (dic_path ,"rb")

def random_word ():
  while True :
    offset =randint (0 ,file_size )
    file_in .seek (offset )
    L =file_in .read (25 ).split ("\r\n")
    if len (L )>2 :
      return L [1 ]

if __name__ =="__main__":
  n =100
  print "%d randomly generated words"%n
  for i in xrange (n ):
    print random_word (),
  print
  file_in .close ()

Note that the file is opened but not read in memory. Only 25 characters are read at a time when a random word is requested.

Ran the above program I get the following error message "There's an error in your program ** ' return outside function (random_word.py, line 13.)
Line 13 - return L [1 ]
What does that message mean "return outside function"?

That will mean that the return is not being properly recognised as inside of the function. This could be an indenting problem or just accidentally having a return statement somewhere else in your program that isnt a function.

here is something that will raise that error

def add(x,y):
    z = x+y
return z

this will work though

def add(x,y):
    z = x+y
    return z

So what is wrong with this code especially line 14 -
There's an error in your program *** 'return' outside function (random_word.py , line 14.)

from os.path import getsize
from random import randint

dic_path ="DictionaryE.txt"
file_size =getsize (dic_path )
file_in =open (dic_path ,"rb")
   
def random_word ():
 while True:
   offset =randint (0 ,file_size )
file_in .seek (offset)
L=file_in .read (25 ).split ("\r\n")
if len (L)>2 :
  return L [1]
if __name__ =="__main__":
  
   n =100
  
   print "%d randomly generated words"%n
  
   for i in xrange (n ):
  
      print random_word (),
   print
  
   file_in .close ()

see the indentation of line 14 and line 13 and line 12 and line 11 do not match the indentation needed to set them all inside the function. You just need to re-write this in a python editor and it should auto-indent it for you.

it should be

def random_word ():
    while True:
        offset =randint (0 ,file_size )
        file_in .seek (offset)
        L=file_in .read (25 ).split ("\r\n")
        if len (L)>2 :
            return L [1]

Thanks error message went away.
Could you recommend which Python editor to use?
Also when I ran the program no error message, but nothing happens.
What am I missing now?

you might have an issue with variables not being global. Try putting this at the start of your program.

global file_in
global file_size

Ok, I put those lines in the beginning of the program. Still got the same result.

what does "DictionaryE.txt" look like? I would like to try and run it but i get an error because i have no "DictionaryE.txt" file.

Instead of the seek method, you could also use a dictionary to assign a number to each word, and then pick a random integer and print the word associated with that integer. IMHO it is preferable to use numbers whenever possible as that is the native language of the computer.

from random import randint
   
def read_file():
   words = {}
   ctr = 0
   dic_path="/usr/local/DictionaryE.txt"
   fileptr =open (dic_path ,"r")
   for rec in fileptr:
      words[ctr] = rec.strip()
      ctr += 1
   fileptr.close()
   return words


if __name__ =="__main__":
 
   word_dictionary = read_file()
   limit = len(word_dictionary) - 1

   n =10
   print "%d randomly generated words from a list of %d\n" % \
         (n, limit)
 
   for i in xrange (n ):
      offset = randint (0, limit )
      word = word_dictionary[offset]
      print offset, word
   print

Ran the program computer outputs 10 random words. But what I want is the computer to pick a random word and the user has to guess it. Computer tells the player how many letters are in the word. The computer can only respond yes or no. Then the player must guess the word.

Ran the program computer outputs 10 random words.

That's all the program was supposed to do. Now you will have to tell the user the number of letters, use a loop to ask for guesses, and compare to letters in the word with the appropriate correct/incorrect response.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.