1. Learn
  2. /
  3. Courses
  4. /
  5. Introduction to Databases in Python

Exercise

Determine the percentage of population by gender and state

In this exercise, you will write a query to determine the percentage of the population in 2000 that comprised of women. You will group this query by state.

Instructions

100 XP
  • Import case, cast and Float from sqlalchemy.
  • Define a statement to select state and the percentage of women in 2000.
    • Inside func.sum(), use case() to select women (using the sex column) from pop2000. Remember to specify else_=0 if the sex is not 'F'.
    • To get the percentage, divide the number of women in the year 2000 by the overall population in 2000. Cast the divisor - census.columns.pop2000 - to Float before multiplying by 100.
  • Group the query by state.
  • Execute the query and store it as results.
  • Print state and percent_female for each record. This has been done for you, so hit 'Submit Answer' to see the result.