City Data Persistence - Python Programming Exercise

In this exercise, you will develop a Python program to create a new version of the "cities database", using persistence to store its data instead of text files. This exercise is perfect for practicing file handling, data storage, and database management in Python. By implementing this program, you will gain hands-on experience in handling file operations, data storage, and database management in Python. This exercise not only reinforces your understanding of file handling but also helps you develop efficient coding practices for managing user interactions.

 Category

Object Persistence Techniques

 Exercise

City Data Persistence

 Objective

Develop a Python program to create a new version of the "cities database", using persistence to store its data instead of text files.

 Example Python Exercise

 Copy Python Code
import sqlite3


class City:
    """Represents a city with a name and population."""

    def __init__(self, name, population):
        """Initialize the city with a name and population."""
        self.name = name
        self.population = population

    def __str__(self):
        """Return a string representation of the city."""
        return f"City: {self.name}, Population: {self.population}"


class CityDatabase:
    """Manages a database of cities."""

    def __init__(self, db_name="cities.db"):
        """Initialize the database connection and create the table if necessary."""
        self.db_name = db_name
        self.connection = sqlite3.connect(self.db_name)
        self.cursor = self.connection.cursor()
        self._create_table()

    def _create_table(self):
        """Create the cities table if it does not exist."""
        self.cursor.execute("""
            CREATE TABLE IF NOT EXISTS cities (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                name TEXT NOT NULL,
                population INTEGER NOT NULL
            )
        """)
        self.connection.commit()

    def add_city(self, city):
        """Add a new city to the database."""
        self.cursor.execute("INSERT INTO cities (name, population) VALUES (?, ?)", (city.name, city.population))
        self.connection.commit()

    def get_all_cities(self):
        """Retrieve all cities from the database."""
        self.cursor.execute("SELECT name, population FROM cities")
        rows = self.cursor.fetchall()
        return [City(name, population) for name, population in rows]

    def delete_city(self, city_name):
        """Delete a city from the database by its name."""
        self.cursor.execute("DELETE FROM cities WHERE name = ?", (city_name,))
        self.connection.commit()

    def update_city_population(self, city_name, new_population):
        """Update the population of a city."""
        self.cursor.execute("UPDATE cities SET population = ? WHERE name = ?", (new_population, city_name))
        self.connection.commit()

    def close(self):
        """Close the database connection."""
        self.connection.close()


# Test Program
if __name__ == "__main__":
    # Initialize the database
    db = CityDatabase()

    # Add new cities
    print("Adding cities to the database...")
    db.add_city(City("New York", 8419000))
    db.add_city(City("Los Angeles", 3980000))
    db.add_city(City("Chicago", 2716000))

    # Retrieve and display all cities
    print("\nCurrent cities in the database:")
    for city in db.get_all_cities():
        print(city)

    # Update a city's population
    print("\nUpdating population of Los Angeles...")
    db.update_city_population("Los Angeles", 4000000)

    # Retrieve and display all cities again
    print("\nCities after update:")
    for city in db.get_all_cities():
        print(city)

    # Delete a city
    print("\nDeleting Chicago...")
    db.delete_city("Chicago")

    # Retrieve and display all cities after deletion
    print("\nCities after deletion:")
    for city in db.get_all_cities():
        print(city)

    # Close the database
    db.close()

 Output

Updating population of Los Angeles...

Cities after update:
City: New York, Population: 8419000
City: Los Angeles, Population: 4000000
City: Chicago, Population: 2716000

 Share this Python Exercise

 More Python Programming Exercises of Object Persistence Techniques

Explore our set of Python Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of Python. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in Python.

  •  Table, Array, and File Management

    In this exercise, you will develop a Python program to expand the tables + array exercise, so that it includes two new methods: dumping the array data into a binary f...

  •  Table Collection and File Management

    In this exercise, you will develop a Python program to expand the exercise (tables + array + files) by creating three classes: Table, SetOfTables, and a test program....

  •  Insect Data Persistence

    In this exercise, you will develop a Python program to create a new version of the "insects" exercise, which should persist the data using some form of storage, such ...