Skip to content

Intermediate Python

👋 Welcome to your new workspace! Here, you can experiment with the data you used in Intermediate Python and practice your newly learned skills with some challenges. You can find out more about DataCamp Workspace here.

On average, we expect users to take approximately 20 minutes to complete the content in this workspace. However, you are free to experiment and practice in it as long as you would like!

1. Get Started

Below is a code cell. It is used to execute Python code. To get you started, there is already pre-written Python code for you to run.

🏃To execute the code, click inside the cell to select it and click "Run" or the ► icon. You can also use Shift-Enter to run a selected cell.

# Create a list of words
word_list = ["Data", "science", "is", "fun!"]

# Loop through the list and print each word
for word in word_list:
    print(word)
# Import the course packages
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# Import two datasets
gapminder = pd.read_csv("datasets/gapminder.csv")
brics = pd.read_csv("datasets/brics.csv")

# Print the first DataFrame
print(gapminder)

3. Write Code

After running the cell above, you have created two pandas DataFrames: gapminder and brics.

Add code to the code cells below to try one (or more) of the following challenges:

  1. Create a loop that iterates through the brics DataFrame and prints "The population of {country} is {population} million!". If you're stuck, try reviewing this video.
  2. Create a histogram of the life expectancies for countries in Africa in the gapminder DataFrame. Make sure your plot has a title, axis labels, and has an appropriate number of bins. If you're stuck, try reviewing this video and this video.
  3. Simulate 10 rolls of two six-sided dice. If the two dice add up to 7 or 11, print "A win!". If the two dice add up to 2, 3, or 12, print "A loss!". If the two dice add up to any other number, print "Roll again!". If you're stuck, try reviewing this video.

Be sure to check out the Answer Key at the end to see one way to solve each problem. Did you try something similar?

Reminder: To execute the code you add to a cell, click inside the cell to select it and click "Run" or the ► icon. You can also use Shift-Enter to run a selected cell.

# 1. Create a loop that prints each country and population in brics
import pandas as pd
brics = pd.read_csv("datasets/brics.csv")
for c, row in brics.iterrows():
    print("the population of " + str(row['country']) + " is " + str(row['population']) + " million!" )
# 2. Create a histogram of life expectancies per country in Africa in gapminder
import matplotlib.pyplot as plt
gapminder = pd.read_csv("datasets/gapminder.csv")
gapminder_africa = gapminder[gapminder.cont == "Afica"]
plt.hist(gapminder_africa.life_exp, bins = 20)
plt.title("Distribution of Life Expectancies in African Countries")
plt.xlabel("Life Expectancy")
plt.ylabel("count")
plt.show()

# 3. Simulate 10 rolls of two six-sided dice
import numpy as np
for x in range(10):
    dice_one = np.random.randint(1, 7)
    dice_two = np.random.randint(1, 7)
    if dice_one + dice_two == 7 or dice_one + dice_two == 11:
        print("A win!")
    elif (
        dice_one + dice_two == 2
        or dice_one + dice_two == 3
        or dice_one + dice_two == 12
    ):
        print("A loss!")
    else:
        print("Roll again!")

4. Next Steps

Feeling confident about your skills? Continue on to Data Manipulation with pandas! This course will help you continue to develop essential data science skills with pandas, and set you up for more advanced techniques such as visualization and machine learning!

5. Answer Key

Below are potential solutions to the challenges shown above. Try them out and see how they compare to how you approached the problem!

# 1. Create a loop that prints each country and population in brics
for lab, row in brics.iterrows():
    print(
        "The population of "
        + str(row["country"])
        + " is "
        + str(row["population"])
        + " million!"
    )
# 2. Create a histogram of life expectancies per country in Africa in gapminder
gapminder_africa = gapminder[gapminder.cont == "Africa"]
plt.hist(gapminder_africa.life_exp, bins=20)
plt.title("Distribution of Life Expectancies in African Countries")
plt.xlabel("Life Expectancy")
plt.ylabel("Count")
plt.show()
# 3. Simulate 10 rolls of two six-sided dice
for x in range(10):
    dice_one = np.random.randint(1, 7)
    dice_two = np.random.randint(1, 7)
    if dice_one + dice_two == 7 or dice_one + dice_two == 11:
        print("A win!")
    elif (
        dice_one + dice_two == 2
        or dice_one + dice_two == 3
        or dice_one + dice_two == 12
    ):
        print("A loss!")
    else:
        print("Roll again!")