Hello i just started learning about python and am beginning a hangman program. I'm trying to read the word from the document then output _ for each letter in it. so far it runs but outputs nothing I'm not sure if I'm formatting it incorrectly or am forgetting something any help would be appreciated.

Thank you,
Acoxia

import string
import linecache 
import random
def find(strng, ch):
    index = 0
    while index < len(strng):
        if strng[index] == ch:
            return index
        index += 1
    return -1


def guessword(word):
    infile = open('words.txt', 'r')
    n =random.random(0,100)
    linecache.getline(infile, n)
                    
    g = len(word)
    y = 0
    i=0

    while y != g: 
        dashes += " _" 
        y += 1

    while i < 6 and find(word, '_') != -1:
       print dashes

I don't see how this can work, since dashes is initially undefined:

while y != g: 
        dashes += " _" 
        y += 1

Perhaps replace that code with the simpler dashes = g * " _" ?

Just a thought but i think the reason nothing happens in your program is the fact that you ask nothing to happen, you make functions but you never call them, to make this work you need something to either call a function that will start it running or at least some code at the end that manages the program.

So, in summary it would be best if you perhaps had a main method that managed the program and make sure to CALL that at the end.

I'm not sure what you're trying to do in your guessword function. It starts out with you opening a file in read mode. So far so good. Then it looks like you're trying to assign a random number to n, where the random number falls between 0 and 100. However, you're using random.random instead of random.randrange() which I don't think will work. I know it isn't working for me in my Python interpreter right now.

Then it looks like you're trying to select a random line from your infile by using linecache.getline. The problem here is that it will return an error because you're trying to read from the file handler. You need to actually read the lines and then select from one of them. Try something like word=linecache.getline(infile.read(), n)

Try this instead. Open up the file and read the contents into a list like this:

infile = open('wordlist','r')
data = infile.read()
listofwords = []
for eachline in data:
    listofwords.append(eachline.strip())
# You have to put a strip on the line because each line has a
# newline at the end.  You want to get rid of that newline.

Now select a random element from the list

selectedword = listofwords[random.randrange(0,len(listofwords))]

Now that you have randomly selected a word, here is an easy way to print a dash for each letter of the word:

for eachletter in selectedword:
    print "-"

# Here is an alternate way of doing it
print "-" * len(selectedword)

Hope that helps.

If the word file is one word per line:

infile = open('wordlist','r')
wordlist = infile.readlines()
infile.close()

You do need to strip() the lines, but I would defer it. You could just strip the word you select, and I like random.choice() to pick one from a list.

selectedword = random.choice(wordlist).strip()

I like mn_kthompson's first example for the dashes as it is more flexible for what you want to do. Here it is, slightly modified to build an output string (ostr) and to print the letter or a dash based on whether or not the letter has been guessed.

ostr = ""
for letter in selectedword:
    if letter in guessedletters:
        ostr += letter + ' '
    else:
        ostr += '- '
print ostr

Or alternatively, put the 'extra' spaces in when you print:

ostr = ""
for letter in selectedword:
    if letter in guessedletters:
        ostr += letter
    else:
        ostr += '-'
print ' '.join(ostr)

Ok thank you all for the replies they have been very helpful. Ive been trying a few of the different ways people suggested but when i output it i get one dash and if print selected word i only receive 1 letter I'm not sure whats doing that . Any advice would be appreciated. Thank you again

import string
import linecache
import random
def find(strng, ch):
    index = 0
    while index < len(strng):
        if strng[index] == ch:
            return index
        index += 1
    return -1




def guessword(word):
    infile = open('desktop/words.txt','r')
    data = infile.read()
    infile.close()


    selectedword = random.choice(data).strip()
    for eachletter in selectedword:
        print "-"                
        print selectedword
guessword("please")

You're still using data = infile.read() so all of the data is in one big blob. Choice wants to pick one of something, so it picks one of the blob.

Change to data = infile.readlines() so you have an array of words and choice will pick one word.

(For debugging this type of application, I usually add an extra print to show me the word it picked and remove it when I'm done testing.)

Few things you should understand first:

1) You are not using find function through out your code i.e. you are not calling it.

2) In the second function: guessword you are taking an arguement, but not processing it. For example: you are passing word in it .. but doing nothing with "word'

Can you write down your algorithm step by step, like what are you trying to accomplish -- that we can definitely get you resolve the problem :-),

take care,


Ok thank you all for the replies they have been very helpful. Ive been trying a few of the different ways people suggested but when i output it i get one dash and if print selected word i only receive 1 letter I'm not sure whats doing that . Any advice would be appreciated. Thank you again

import string
import linecache
import random
def find(strng, ch):
    index = 0
    while index < len(strng):
        if strng[index] == ch:
            return index
        index += 1
    return -1




def guessword(word):
    infile = open('desktop/words.txt','r')
    data = infile.read()
    infile.close()


    selectedword = random.choice(data).strip()
    for eachletter in selectedword:
        print "-"                
        print selectedword
guessword("please")

A personal preference would be to use a list for the printed portion.

word = "alphabetical"   ## simulate getting a word from the file
guess_list = []
for j in range(0, len(word)):
   guess_list.append("_")
#
#   Ask for a guess, etc.
#   Guess is incorrect
guess_word = "".join(guess_list)
print guess_word
#
# Simulate letter "P" is guessed and the third element of the
# list is replaced with the correct letter
guess_list[2]="p"
guess_word = "".join(guess_list)
print guess_word
#
# More visually appealing?
guess_word = " ".join(guess_list)
print guess_word

You would of course have functions to do most of this and call the "check_if_the_letter_is_correct" function, or the "print_guess_word" function instead of one long program.

One day we should write the ultimate hangman program in this forum. It looks like a recurrent theme in CS classes :)

Ah, but the goal is for THEM to write it :icon_smile:

I like this approach.

Thanks,
-Ashu

A personal preference would be to use a list for the printed portion.

word = "alphabetical"   ## simulate getting a word from the file
guess_list = []
for j in range(0, len(word)):
   guess_list.append("_")
#
#   Ask for a guess, etc.
#   Guess is incorrect
guess_word = "".join(guess_list)
print guess_word
#
# Simulate letter "P" is guessed and the third element of the
# list is replaced with the correct letter
guess_list[2]="p"
guess_word = "".join(guess_list)
print guess_word
#
# More visually appealing?
guess_word = " ".join(guess_list)
print guess_word

You would of course have functions to do most of this and call the "check_if_the_letter_is_correct" function, or the "print_guess_word" function instead of one long program.

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.