DEV Community

Cover image for Make a Fun CLI Project
Angela Palaszewski
Angela Palaszewski

Posted on

Make a Fun CLI Project

Why CLI?

When I was told that my bootcamp python project was going to be a CLI project, I was concerned and apprehensive. Coming from learning React, I got really into the design and look of a project. Now switching gears to a backend project with no pizazz, I had no idea how to tackle this. This project really did help me understand functionality better, so I am happy I did it!

Are you ready to dive into the world of command-line quizzes? In this blog post, we'll embark on an adventure to create an interactive quiz using the powerful combination of Python and SQLAlchemy. We'll even add some art, color and sounds to jazz it up a bit! Get ready to challenge your knowledge and experience the magic of these technologies!

Setting the Stage

The stage is set for an epic command-line quiz! We'll be using Python, a versatile programming language known for its simplicity and flexibility, to create our quiz application. But we won't stop there – to give our quiz a solid foundation, we'll integrate SQLAlchemy, a robust and intuitive Object-Relational Mapping (ORM) library.

Building the Castle of Questions

Every quiz needs a collection of mind-bending questions. With SQLAlchemy, we can effortlessly design and manage a database to store our questions. We'll create a table using SQLAlchemy's powerful declarative syntax, defining the fields for each question and its corresponding answer. Prepare to be captivated by the elegance and efficiency of SQLAlchemy's database handling capabilities.

class Question(Base):
    __tablename__ = 'questions'

    id = Column(Integer(), primary_key=True)
    question = Column(String())
    answer_a = Column(String())
    answer_b = Column(String())
    value_a = Column(Integer())
    value_b = Column(Integer())
    value_c = Column(Integer())
    value_d = Column(Integer())

    def __repr__(self):
        return f"{self.question} \n" \
            + f"a. {self.answer_a} \n" \
            + f"b. {self.answer_b} \n" \
            + "c. Neither \n" \
            + "d. Either/Both \n"

Enter fullscreen mode Exit fullscreen mode

The Journey Begins: User Interaction

As we embark on our quiz journey, we'll guide users through an interactive experience. With Python's built-in input() function, we can prompt users to enter their name and start the quiz. We'll leverage the flexibility of Python's control structures, such as loops and conditionals, to create an engaging and dynamic user experience.

in_game = False
while True:
    username_input = input ("What is your name?  ")
    if username_input == "":
        print("Error: Please enter a valid name.")
    else:
        in_game = True

        #instructions
        if in_game is True:
            print (f"\nHello {username_input}!")

Enter fullscreen mode Exit fullscreen mode

Randomness Unleashed: Generating Random Questions

What's a quiz without randomness? Using Python's random module, we'll spice things up by randomly selecting questions from our SQLAlchemy database. This ensures each quiz session offers a unique and exciting experience. No two quizzes will be the same!

def generate_questions():
    random_questions = session.query(Question).order_by(func.random()).limit(6).all()
    return random_questions

answers = []
random_questions = generate_questions()
index = 0
      #creating random questions
      while index < len(random_questions):
           question = random_questions[index]
           print (f"\n{question}")
           q_input = input("Your answer: \n").lower()

Enter fullscreen mode Exit fullscreen mode

Validation: Ensuring Correct Answers

It's time to put our users' knowledge to the test. With Python's conditional statements, we'll compare user input against the correct answer stored in the database. We'll handle incorrect answers gracefully, providing helpful feedback and encouraging users to try again. After all, learning is all about embracing challenges and growing from them.

if q_input == "a":
   answers.append(question.value_a)
   index += 1
elif q_input == "b":
   answers.append(question.value_b)
   index += 1
elif q_input == "c":
   answers.append(question.value_c)
   index += 1
elif q_input == "d":
   answers.append(question.value_d)
   index += 1
else:
   print ("\nAnswer a, b, c, or d")

Enter fullscreen mode Exit fullscreen mode

Score Tracking: Celebrating Success

Everyone loves a bit of healthy competition! We'll track users' scores using Python variables and provide a final score at the end of the quiz. With SQLAlchemy, we can even store these scores in the database for future reference. So, whether users aim for a perfect score or simply want to enjoy the journey, our quiz has them covered.

Adding the Pizazz!

Using some additional packages, not only can you make a functional, fun CLI quiz, but you can also add some color and sound! Colorama allows you to add different color text, background and weights to your font. Playsound lets you add different sound effects if you want some added flair with mp3's.

That's a Wrap

Congratulations! You have successfully ventured through the process of creating a captivating command-line quiz using Python and SQLAlchemy. We've explored the seamless integration of these technologies, from designing the database to generating random questions and validating user answers. Through this project, you've witnessed the power of Python's simplicity and flexibility, combined with SQLAlchemy's elegance and efficiency.

So, what are you waiting for? It's time to embark on your own quiz creation adventure. Unleash your creativity, challenge your users, and let Python and SQLAlchemy be your guides. Happy quizzing!

Top comments (0)