Write a Python Program to Repeatedly Prompt the User to Enter the Capital of a State

Are you ready to put your knowledge of state capitals to the test? Look no further! In this Python programming tutorial, we will guide you through the process of creating an interactive quiz that prompts the user to enter the capital of a state (Guess the capitals) . With a little bit of coding magic, we'll determine if the user's answer is correct or not. So, buckle up, and let's embark on this educational and exciting journey!

Python program  Dictionary Programming skills Guess the number


Table of Contents 

  • Introduction
  • Why Python?
  • Python problem
  • Step 1: Define the States and Capitals
  • Step 2: Create the Main Program
  • Step 3: Running and Testing the Program
Python is a versatile programming language that allows you to create interactive programs. This program will test your knowledge of state capitals by repeatedly prompting you to enter the capital of a state. It will provide immediate feedback on whether your answer is correct or not. This program is a great way to enhance your Python skills while having fun and learning about state capitals.

Why Python?

Python is a high-level, interpreted programming language that has gained immense popularity among developers, data scientists, and software engineers in recent years. Created by Guido van Rossum and first released in 1991, Python emphasizes readability, simplicity, and versatility, making it an excellent choice for both beginners and experienced programmers. In this blog post, we will explore why Python is essential for data analysis, machine learning, and web development.

Python problem: (Guess the capitals) 

Write a program to repeatedly prompt the user to enter the capital of a state. Upon receiving the user’s input, the program reports whether the answer is correct. Assume the states and their capitals are stored in dictionaries as key-value pairs.  

Step 1: Define the States and Capitals

To begin, we need to define the states and their corresponding capitals. We can store this information in a dictionary as key-value pairs. Here's an example:

| Practical List - Python Tutorial [ 4330701 ] [ PRACTICAL EXERCISES ]  

python code: 

states_capitals = {

    "Alabama": "Montgomery",

    "Alaska": "Juneau",

    "Arizona": "Phoenix",

    "Arkansas": "Little Rock",

    "California": "Sacramento",

    # Add more states and capitals here

}

Feel free to add more states and capitals to the dictionary to expand the program's scope.

Step 2: Create the Main Program

Next, we will create the main program that will run the state capitals quiz. We can define a function called state_capitals_quiz() to encapsulate the program logic. Here's an outline of the function:

python code:

def state_capitals_quiz():

    # Initialize variables for score and total questions

    score = 0

    total_questions = 0


    # Prompt the user for input and check the answer

    while True:

        # Prompt the user for a state

        state = input("Enter the name of a state (or 'quit' to exit): ")


        # Check if the user wants to quit

        if state.lower() == "quit":

            break


        # Check if the state is in the dictionary

        if state in states_capitals:

            # Prompt the user for the capital

            capital = input("What is the capital of {}? ".format(state))


            # Check the user's answer

            if capital.lower() == states_capitals[state].lower():

                print("Correct!")

                score += 1

            else:

                print("Incorrect. The capital of {} is {}.".format(state, states_capitals[state]))


            total_questions += 1

        else:

            print("Invalid state. Please try again.")


    # Display the final score

    print("Quiz ended.")

    print("Score: {}/{}".format(score, total_questions))

| Learn Python Online with " Computer Courses - All in One " 

Running and Testing the Python Program:

Now that our program is complete, let's run it and put it to the test! To do so, simply call the state_capitals_quiz() function.

state_capitals_quiz()

Output: Python Program to Repeatedly Prompt the User

Enter the name of a state (or 'quit' to exit): alabama

Invalid state. Please try again.

Enter the name of a state (or 'quit' to exit): Alabama

What is the capital of Alabama? Montgomery

Correct!

Enter the name of a state (or 'quit' to exit): exit

Invalid state. Please try again.

Enter the name of a state (or 'quit' to exit): quit

Quiz ended.

Score: 1/1

FAQs:

How to handle user input errors in the program ?

When handling user input errors in a Python program, you can use the try-except block to catch and handle specific exceptions that may occur. Here's how you can modify the program to handle user input errors:

python code:

 # Define the dictionary of states and their capitals states_capitals = { "Alabama": "Montgomery", "Alaska": "Juneau", # Add more states and capitals here } # Prompt the user to enter the capital of a state while True: state = input("Enter the name of a state (or 'quit' to exit): ") if state == "quit": break try: capital = input("What is the capital of " + state + "? ") if capital == states_capitals[state]: print("Correct!") else: print("Incorrect. The capital of " + state + " is " + states_capitals[state] + ".") except KeyError: print("Invalid state. Please try again.") In this modified version, we use a try-except block to catch a KeyError exception that may occur if the user enters an invalid state. If a KeyError is raised, it means that the entered state is not present in the states_capitals dictionary. In this case, we print an error message and prompt the user to try again.

By handling the KeyError exception, we prevent the program from crashing and provide a more user-friendly experience. This way, if the user enters an invalid state, they will receive feedback and can make another attempt.

Handling user input errors is important to ensure the program's robustness and improve the user experience. By using the try-except block, you can gracefully handle exceptions and guide the user toward correct input.

In the world of programming, speed, and efficiency are crucial factors that can make or break your code. As a Python developer, it's essential to constantly strive for better coding practices that can optimize your programs and improve their performance. 

| Practical List - Python [ 4330701 ] [ PRACTICAL EXERCISES ]  

Post a Comment

0 Comments