4
\$\begingroup\$
answer = input("what's the word")
answer_list = list(answer) #list version of the original word
presentation = []
for i in range(len(answer_list)):
    presentation.append("_") #makes a list that shows the progress of the player during the game

incorrect = 0 #number of allowed guesses
completion = False # condition for end game
while completion == False:
    attempt = input('guess')
    ind = 0 #index of the guess that appears in answer_list
    count = 0 #number of occurences of the guess in answer_list
    for x in answer_list: #searches for all occurences of the guess in answer_list and change presentation accordingly
        if x == attempt:
            num = answer_list.index(attempt)
            presentation[num] = attempt
            answer_list[num] = 0 #if there is an occurence, replace that occurence with 0 in answer_list
            count += 1
    if count>0:
        print ("Your guess is correct, there was/were {} matches in the word".format(count))
        print(presentation)
    elif count == 0:
        incorrect += 1

    if incorrect == 5:
        print("You lost")
        break
    
    if any(answer_list) == False: #since all 0 have a negative truthy value, we can use any() to check if any element has a truthy value 
        print("Congrats, you got everything correct")
        completion = True
        break

I want to make clean up this hangman game and format it as 1 or 2 functions. How do I make it work? For example, initializing lists could be initialize() and from the declaration of incorrect to the end of the code can be play_hangman(). I am still very new to python.

\$\endgroup\$
5
  • 1
    \$\begingroup\$ Welcome to the Code Review site where we review your working code and provide suggestions on how that working code can be improved. I agree that should should create functions, but we can't tell you how to do that. If you want a review of the current code we can do that. Please read our guidelines on what makes a good question and what we can can can't help you with. \$\endgroup\$
    – pacmaninbw
    Commented Oct 29, 2020 at 1:21
  • 1
    \$\begingroup\$ This code doesn't work. I run it, it asks me for the word, and fails immediately afterwards. \$\endgroup\$
    – C. Harley
    Commented Oct 29, 2020 at 12:29
  • \$\begingroup\$ @C.Harley Is there an error when it fails? If so, what is the error? I tried running it on onlinegdb.com and saw no failure as you described \$\endgroup\$ Commented Oct 29, 2020 at 16:27
  • \$\begingroup\$ For anyone voting refactor requests as off-topic: please see answers to this relevant meta. \$\endgroup\$ Commented Oct 29, 2020 at 17:18
  • \$\begingroup\$ The error was "NameError: name 'dog' is not defined" when I used the word dog. This is in both python 2.7.16 and 3.6.1 - I added 3.8.5 this morning, the code worked in that version. \$\endgroup\$
    – C. Harley
    Commented Oct 30, 2020 at 12:02

1 Answer 1

4
\$\begingroup\$

Welcome to Code Review!

PEP-8

Since you're still new to python, it's a good idea to keep a window/tab open with PEP-8 loaded into it. It is mostly suggestions for coding style. Few things that can be picked up from the same:

  • Comparisons to singletons like None should always be done with is or is not, never the equality operators.
  • Comments should be complete sentences. The first word should be capitalized, unless it is an identifier that begins with a lower case letter (never alter the case of identifiers!).
  • PEP 257 describes good docstring conventions. Note that most importantly, the """ that ends a multiline docstring should be on a line by itself:

Functions

As you've already raised this point, splitting the code into individual functions is always a good practice.

if __name__ block

Put the execution logic of your script inside the if __name__ == "__main__" block. Read more about the details on why on stack overflow.

f-string

Python 3.x also introduced literal string interpolation, or more commonly used term: f-string. Read more about it here (PEP-498).

Type hinting

When writing functions, you can also make use of type hinting to provide a more readable flow of your code to anyone. This helps removing the manual labour of having to backtrack variable types etc. More details can be found in PEP-484.

Game logic

The initialisation of presentation array can be simplified to:

presentation = ["_"] * len(answer)

For every guessed character from the user, you keep looping over the answer_list, irrespective of validating whether the guess is correct or not.

Before the loop over each character of the correct word, you have setup ind = 0 which is never really used.

Your global while loop relies on the condition completion == False (which should ideally be completion is False) but you break out before the loop/condition really has a chance to do so for you, making the variable useless.


Rewrite

from typing import List

MAX_ATTEMPTS: int = 5


def get_answer() -> str:
    return input("What's the word? ")


def correct_guess(char_count: int, guessed_word: List[str]):
    print(f"Your guess is correct, there was/were {char_count} matches in the word.")
    print(" ".join(guessed_word))


def game_win(guessed_word: List[str]) -> bool:
    return "_" in guessed_word


def game():
    answer = get_answer()
    correct_letters = set(answer)
    guessed_word = ["_"] * len(answer)
    incorrect = 0
    while True:
        if incorrect >= MAX_ATTEMPTS:
            print("You lost!")
            break
        attempt = input("Guess: ")
        if attempt not in correct_letters:
            incorrect += 1
            continue
        char_count = 0
        for index, char in enumerate(answer):
            if char == attempt:
                guessed_word[index] = char
                char_count += 1
        correct_guess(char_count, guessed_word)
        if game_win(guessed_word):
            print("Congrats, you got everything correct")
            break


if __name__ == "__main__":
    game()
\$\endgroup\$
2
  • \$\begingroup\$ We aren't supposed to provide a code writing service. \$\endgroup\$
    – pacmaninbw
    Commented Oct 30, 2020 at 12:30
  • 2
    \$\begingroup\$ @pacmaninbw I was just bored at work.... \$\endgroup\$
    – hjpotter92
    Commented Oct 30, 2020 at 12:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.