Magic-8-ball project (Python 3) - Feedback

Hey guys!
Im just a beginner and Id like some feedback and comments on the code for magic-8-ball project, how can i make it better and/or cleaner? Is there any ways to optimize it?
https://www.codecademy.com/workspaces/639b19a6263c76afb4544d4d

Your implementation is great!
As part of the feedback loop, I would suggest decoupling furthermore your code and some functions to enhance the readability and maintenance of your code. For example:

import random

magic_ball_answers = ["Yes - definitely",
                      "It is decidedly so",
                      "Without a doubt",
                      "Reply hazy, try again",
                      "Ask again later",
                      "Better not tell you now",
                      "My sources say no",
                      "Outlook not so good",
                      "Very doubtful",
                      "There is no hope"]


def is_another_question_valid_response(answer, yes_options, no_options):
    if answer not in yes_options and answer not in no_options:
        print("\nAccepted answers are: `yes`,`y`, `no` and `n`")
        another_question(input("\n\nDo you want to ask again?  y/n\n"))


def another_question(answer):
    """
    Description: Reference to loop(), resets software loop for another question.
    """
    yes_options = ["yes", "y"]
    no_options = ["no", "n"]
    answer = answer.lower()
    is_another_question_valid_response(answer, yes_options, no_options)
    if answer in yes_options:
        init_game()
    elif answer in no_options:
        print("Bye!")
        print("If you`ll have another question type in `ask()`")


def ask_for_name():
    return input("\nWhat`s your name? ")


def ask_for_question(name):
    question = input("What is your question? ")
    if question == "":
        if name == "":
            name = "stranger"
        print(f"\nHi {name}.")
        print("You didn`t ask question. Try again!")
        return ask_for_question(name)
    return question


def ask():
    name = ask_for_name()
    question = ask_for_question(name)
    return name, question


def generate_random_number():
    return random.randint(0, 9)


def generate_magic_8ball_answer():
    return magic_ball_answers[generate_random_number()]


def magic_8ball(asked_info):
    name, question = asked_info
    print("\n" + name + " asks: " + question)
    print("Magic 8-Ball's answer: " + generate_magic_8ball_answer())
    another_question(
        input("\n\nDo you want to ask again? y/n\n")
    )


def init_game():
    """
    :return:
    """
    magic_8ball(ask())


if __name__ == "__main__":
    init_game()

With decoupling, testing, and debugging your code would become easier. I would suggest reading about TDD (Test Driven Development) using python pytest.

1 Like

Your code looks much cleaner and easy to read. Thank you for your feedback! It`s really helpful!

1 Like