6
\$\begingroup\$

I have recently been diving into Python. I have been making really small programs like this one and I am not confident in how practical I am writing Python. This is because I am not familiar with the indent block coding.

Do I have any redundancies? Is there too much stuff going on in the game function?

import random

def getRandom():
    # will get a random word out of list of words

    answerList = ['toy', 'plane', 'bannana', 'wedding',
                'computer']

    random.shuffle(answerList)

    answer = list(answerList[0])

    return answer


def parseGuess(guess):


    guess = list(guess)


    if len(guess) == 1:
        return True
    else:
        return False


def playAgain(stats):

    print(stats["Tries"])

    print("\n It took you {} tries to guess {}".format(stats["Tries"], stats["Words"][0]))

    user = input("Would you like to play again Y/n: ").lower()

    if user != 'y':
        print("Thanks for playing. Bye")

    else:
        game()

def game():

    correctAnswerCount = 0
    answer = getRandom()

    usedLetters = []

    display = []

    display.extend(answer)


    stats = {
        "Words": [],
        "Tries": 0
    }

    # CONVERT EVERY ELEMENT IN THE DISPLAY LIST TO AN UNDERSOCORE

    for i in range(len(answer)):

        display[i] = "_"


    print("========== \n{}\n==========".format(" ".join(display)))
    print("\nCorrect answerCount: {}/{}".format(correctAnswerCount, len(answer)))



    while correctAnswerCount < len(answer):
        guess = input("Please only choose a letter: ").lower()

        stats["Tries"] += 1



        # CHECK TO SEE IF THE USER ONLY ENTERED ONE LETTER
        if parseGuess(guess):

            usedLetters.append(guess)

            for i in range(len(answer)):
                if guess == answer[i]:
                    display[i] = guess
                    correctAnswerCount += 1

        else:
            guess = input("Please only choose ONE a letter: ").lower()

        print("========== \n{}\n==========".format(" ".join(display)))
        print("\nCorrect answerCount: {}/{} \n ".format(correctAnswerCount, len(answer)))
        print()
        print(" letters used: \n{}".format(" ".join(usedLetters)))

    stats["Words"].append("".join(answer))

    print("Well done you guessed the corrext word")


    playAgain(stats)



game()
\$\endgroup\$
5
\$\begingroup\$

Built-in functions

You don't need the getRandom() function, as Python already has one. It is called random.choice(answerList).

Boolean expressions

If you return a boolean value based on an expression, don't write

if len(guess) == 1:
    return True
else:
    return False

Instead, just write return len(guess) == 1.

Naming

The Python convention for function names is lower_case_with_underscores, also called snake case. I suggest you look up PEP8, which is the official Python Style Guide. Also Google's Python Style Guide is pretty popular.

Your method names are not very well chosen, because they don't tell the reader what they do. parseGuess returns a boolean (true or false) value, so a better name would be has_length_one or is_single_item. But since the function can be reduced to an inline len(guess) == 1, I suggest even removing the function and using the simple boolean expression instead.

The following is also very misleading:

user = input("Would you like to play again Y/n: ").lower()

The input is not the user. You could call it user_input, but even that seems redundant. Since the intent of that line is to ask the user whether to play again or not, you could just call the variable play_again, then check whether if play_again == 'y': ...

Pythonic code

Code is considered pythonic, if it uses the language's features appropriately and thus is more readible to people familiar with Python. For example

display = []
display.extend(answer)
for i in range(len(answer)):
    display[i] = "_"

is not pythonic, because it uses an explicit iteration counter. Instead you can use a list comprehension and make it much shorter and more readible, like this:

display = ["_" for _ in answer]

This uses _ as a throwaway variable and assigns a new list to display that contains an "_" for every item (i. e. character) in answer.

Another one liner that would achieve the same would be display = ["_"] * len(answer), however I would prefer the former one.

\$\endgroup\$
  • \$\begingroup\$ Thank you, I just tried both of these out and was able to delete the parseGuess and getRandom functions. \$\endgroup\$ – Champa Dec 16 '17 at 21:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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