brittAnderson / Intro2Computing4Psychology

A guided introduction to computing tools useful for research in psychology - targeted to complete beginners
46 stars 159 forks source link

Beginner Hangman Python #58

Closed isimione closed 3 years ago

isimione commented 3 years ago

Below I've attached the very rough beginnings of my hangman python. I'm having trouble specifying the print function to only the guessed letters (instead I get outputs ranging from 8 of the guessed letters (e.g.,e,e,e,e,e,e,e,e), indexes on the chosen word (e.g., 0,1,2,3,4,5,6,7) I've also found that outputs sometimes switch myword = "elephant" max_guesses = 5 mylistname = list(myword) for letter in mylistname: print("Guess a letter in the word, then press enter:") guess = input() if guess in mylistname: for i,j in enumerate(mylistname): print(i) I've tried some potential reiterations e.g., print(i.guess)

brittAnderson commented 3 years ago

Python cares about whitespace, so we can't run your code without knowing how it is indented. If you look at the menus for writing issues you can use the <> to insert code blocks like:

myword = "elephant"
max_guesses = 5
mylistname = list(myword)
for letter in mylistname:
    guess = input("Guess a letter in the word, then press enter:")
    if guess in mylistname:
        for i,j in enumerate(mylistname):
            print(i)

Note that you can use your prompt in the "input" command. Also "enumerate" returns a "pair". The first is the index number and the second is the letter (in your case that would be "j"). Can you tell me again what you expect to see when this code runs? Understanding at the level of input -> output can help you (and me) puzzle out what has to go in between.

brittAnderson commented 3 years ago

Another thought. You are looping through each letter in your word. You probably want that top for loop to be once for each permissible guess.

isimione commented 3 years ago

I want my code to produce the guess again (for example e), but then also produce the index position associated with the guess (for example (1,3) for e. So if someone inputted e, I would want to output to be (1,3, 'e') or something similar. I'm having trouble figuring out how to specify the output to the inputted guess as opposed to the 'myword'.

brittAnderson commented 3 years ago

Is this what you want?

def whereMatch (l,word):
   mis = []
   for w in enumerate(word):
      if l == w[1]: mis.append(w[0])
   return(mis,l)

When I use this:

whereMatch ("e", "elephant") ([0, 2], 'e') whereMatch ("z", "elephant") ([], 'z')

If the first element is an empty list (length 0) then there were no matches. Otherwise I get a list of the locations in the word where it matched and in the second position of the tuple the letter I was checking. I used here the enumerate function we learned about. Also, I put it in a function so that you can use it in your code. You could use the index list to update a display for the user with the letter for instance.