Featured resource
2026 Tech Forecast
2026 Tech Forecast

1,500+ tech insiders, business leaders, and Pluralsight Authors share their predictions on what’s shifting fastest and how to stay ahead.

Download the forecast
  • Lab
    • Libraries: If you want this lab, consider one of these libraries.
    • Data
Labs

Perform Basic Calculations for Data Analysis in Python

In this lab, you'll turn a handful of raw product values into a clear weekly profit report using nothing but core Python. You'll store product details in variables, fix the type error that appears when numbers arrive as text, calculate revenue, cost, and profit margin, check the results against targets, and present everything in a readable summary with f-strings.

Lab platform
Lab Info
Level
Beginner
Last updated
Nov 13, 2026
Duration
45m

Contact sales

By clicking submit, you agree to our Privacy Policy and Terms of Use, and consent to receive marketing emails from Pluralsight.
Table of Contents
  1. Challenge

    Step 1: Assign product details to variables

    Every analysis starts with raw values, and the first job is giving them names you can work with. In this lab, you'll take one product's weekly sales details, which arrive as loose values with some of them stored as text, and turn them into a short profit report for a retailer's weekly review. Along the way, you'll convert text to numbers, calculate revenue, cost, and profit margin, check the results against targets, and format the final summary with f-strings.

    To begin, you'll store the product's details in variables. A variable is a name that points to a value, so unit_price can stand in for the product's price everywhere you use it. By the end of this step, you'll have four named values and know which of them Python treats as numbers and which it treats as text. The workspace contains a single notebook, product_margin_report.ipynb, whose code cells are partly written, with a ____ placeholder marking each piece you type yourself. Open product_margin_report.ipynb from the File Explorer, then run all of the code cells in this step by selecting each one in turn and pressing Shift+Enter.

    info> Feeling stuck? Open product_margin_report_solution.ipynb from the File > Open menu to see every cell completed. Give each blank a try on your own first. The solution notebook is your safety net, not your starting point.

    Replace every ____ in a cell before you run it. If you run a cell with a placeholder still in it, Python stops with NameError: name '____' is not defined, which means the blank still needs your code.

    The first code cell already assigns product_name and unit_price. Quotes around a value mark it as text, which is how the price arrived from the order form:

    product_name = "Trail Water Bottle"
    unit_price = "24.99"  # copied from an order form
    unit_cost = ____
    units_sold = ____  # copied from a spreadsheet export
    

    Complete the two remaining assignments, then run the cell:

    • Replace the ____ after unit_cost with the number 9.50, typed without quotes.
    • Replace the ____ after units_sold with the text "120", typed in quotes exactly as it arrived from the spreadsheet.

    The cell produces no output, because an assignment only stores a value.

    The next cell prints each variable with the built-in print() function. There's nothing to type in it. Run it:

    print(product_name)
    print(unit_price)
    print(unit_cost)
    print(units_sold)
    

    You'll see four lines: Trail Water Bottle, 24.99, 9.5, and 120. In this output, 24.99 and 120 look like ordinary numbers.

    Output alone can be misleading. The built-in type() function reports what kind of value a variable holds, and the next cell already checks the first three variables:

    print(type(product_name))
    print(type(unit_price))
    print(type(unit_cost))
    print(____)
    

    Replace the ____ with a type() call on units_sold, then run the cell.

    You'll see <class 'str'> for product_name, unit_price, and units_sold, and <class 'float'> for unit_cost.

    If units_sold shows <class 'int'> instead, you typed 120 without quotes. Add the quotes in the first cell, then run that cell and this one again.

    A str, short for string, is text, even when every character in it is a digit. A float is a number that can have a decimal part. Two of the values you need for calculations are actually strings, which sets up the next step.

  2. Challenge

    Step 2: Convert text values to numbers

    With the product details stored in named variables and their types confirmed, you can start calculating. Here, you'll try to calculate revenue with the values exactly as they arrived, read the error Python reports, and fix it by converting the text values to numbers. By the end of this step, unit_price and units_sold will hold numeric values that arithmetic works with. Revenue is the unit price multiplied by the number of units sold. The next cell tries that calculation with the * operator, and there's nothing to type in it. This cell is meant to fail: Python does not treat a string as a number just because its characters are digits, so multiplying two strings is not a valid operation. Run it:

    revenue = unit_price * units_sold
    

    The cell stops with a TypeError whose last line reads TypeError: can't multiply sequence by non-int of type 'str'.

    Read an error message from the bottom up. TypeError names the category of problem: an operation was used on a type of value that doesn't support it. The word "sequence" is how Python refers to the string in unit_price, and 'str' is the type of units_sold. The error stops only this cell, so you continue by running the next cell. The notebook tags this cell raises-exception so that running the whole notebook top to bottom does not halt here.

    Not every operation between a string and a number fails, though. Multiplying a string by an int is allowed, and it repeats the text. The next cell multiplies unit_price, which is still a string, by 3. There's nothing to type in it. Run it:

    unit_price * 3
    

    You'll see '24.9924.9924.99', the price text written three times, and no error. If units_sold had been the integer 120 instead of the text "120", the revenue cell would have run without complaint and stored the price text repeated 120 times. A wrong result with no error is harder to catch than a failed cell, which is why checking each variable's type with type() before calculating matters.

    To fix the problem, convert each text value to the numeric type that fits it. A price can have cents, so unit_price needs to become a decimal number, and the built-in float() function converts a value to one. The next cell stores the converted value back in the same variable:

    unit_price = ____
    

    Replace the ____ with a call to float() on unit_price, then run the cell.

    The cell produces no output.

    A count of items sold never has a fractional part, so units_sold needs to become a whole number, and the built-in int() function converts a value to one:

    units_sold = ____
    

    Replace the ____ with a call to int() on units_sold, then run the cell.

    The cell produces no output.

    The next cell prints the type of both converted variables. Run it:

    print(type(unit_price))
    print(type(units_sold))
    

    You'll see <class 'float'> for unit_price and <class 'int'> for units_sold, confirming that both conversions worked.

  3. Challenge

    Step 3: Calculate revenue, cost, and profit margin

    Now that every number is stored as a numeric type, Python's arithmetic operators work on them the way you'd expect: * multiplies, - subtracts, and / divides. Here, you'll write the calculation for each of the four figures the weekly review needs. Revenue and total cost come straight from the product details, and profit and profit margin build on those two. By the end of this step, you'll have the product's revenue, total cost, profit, and profit margin stored in variables. When the last line of a cell is a variable name on its own, Jupyter displays that variable's value below the cell. Each cell in this step already names its variable and displays it on the last line, so you type only the calculation.

    Revenue is the unit price multiplied by the number of units sold:

    revenue = ____
    revenue
    

    Replace the ____ with an expression that multiplies unit_price by units_sold, then run the cell.

    You'll see 2998.7999999999997.

    You might expect 2998.8. Computers store most decimal numbers as close binary approximations, so tiny rounding differences like this are normal. You'll clean up how the number is displayed when you format the report.

    Total cost is the unit cost multiplied by the number of units sold:

    total_cost = ____
    total_cost
    

    Replace the ____ with an expression that multiplies unit_cost by units_sold, then run the cell.

    You'll see 1140.0.

    Profit is what remains of revenue after costs:

    profit = ____
    profit
    

    Replace the ____ with an expression that subtracts total_cost from revenue, then run the cell.

    You'll see 1858.7999999999997.

    Profit margin is profit divided by revenue: the share of each dollar of revenue that is profit.

    profit_margin = ____
    profit_margin
    

    Replace the ____ with an expression that divides profit by revenue, then run the cell.

    You'll see 0.6198479391756703, meaning about 62 cents of every dollar of revenue is profit.

  4. Challenge

    Step 4: Compare results against target values

    With revenue and profit margin calculated, you can answer the review's next question: did the product hit its targets? Here, you'll compare your results against the store's targets with comparison operators. By the end of this step, you'll have two True or False answers that say whether each target was met. The store expects at least $2,500 in weekly revenue and a profit margin of at least 65%. Because profit_margin is stored as a decimal, the margin target is stored the same way, as 0.65. The next cell stores both targets, and there's nothing to type in it. Run it:

    revenue_target = 2500.00
    margin_target = 0.65
    

    The cell produces no output.

    A comparison operator compares two values and produces a boolean, a value that is either True or False. The >= operator checks whether the value on its left is greater than or equal to the value on its right. The next cell stores the revenue check in met_revenue_target:

    met_revenue_target = ____
    met_revenue_target
    

    Replace the ____ with a comparison that checks whether revenue is greater than or equal to revenue_target, then run the cell.

    You'll see True, because the product earned more than the revenue target.

    The next cell stores the margin check in met_margin_target:

    met_margin_target = ____
    met_margin_target
    

    Replace the ____ with a comparison that checks whether profit_margin is greater than or equal to margin_target, then run the cell.

    You'll see False, because a margin of about 62% falls short of 65%.

  5. Challenge

    Step 5: Report results with f-strings

    Your calculations and target checks are complete, but raw output such as 2998.7999999999997 and 0.6198479391756703 isn't something you'd paste into a review. Here, you'll write f-strings to place variables inside text and format specifiers to control how numbers appear. By the end of this step, you'll have a clear, multi-line summary of the product's week. An f-string is a string with the letter f before the opening quote. Inside it, any variable name wrapped in curly braces is replaced with that variable's value, so f"Hello, {name}" becomes Hello, Ada when name holds "Ada". The next cell prints the report's heading:

    print(____)
    

    Replace the ____ with an f-string that reads Weekly summary: followed by product_name in curly braces, then run the cell.

    You'll see Weekly summary: Trail Water Bottle.

    A format specifier goes after a colon inside the curly braces and controls how a number appears. The specifier :,.2f adds a thousands separator and rounds to two decimal places, which is how currency is usually shown. In the next cell, the f-string is already written, and the $ before the braces is ordinary text in the string:

    print(f"Revenue: ${____}")
    

    Replace the ____ with revenue followed by the :,.2f specifier, then run the cell.

    You'll see Revenue: $2,998.80.

    The specifier :.1% multiplies a number by 100, rounds it to one decimal place, and adds a percent sign:

    print(f"Profit margin: {____}")
    

    Replace the ____ with profit_margin followed by the :.1% specifier, then run the cell.

    You'll see Profit margin: 62.0%.

    The final cell puts it all together with one f-string per line of the report, and most of it is already written:

    print(f"Weekly summary: {product_name}")
    print(f"Revenue: ${revenue:,.2f}")
    print(f"Total cost: ${____}")
    print(f"Profit: ${____}")
    print(f"Profit margin: {profit_margin:.1%}")
    print(f"Met revenue target: {met_revenue_target}")
    print(f"Met margin target: {____}")
    

    Fill in the three remaining placeholders, then run the cell:

    1. On the Total cost line, replace the ____ with total_cost followed by the same currency specifier you used for revenue.
    2. On the Profit line, replace the ____ with profit followed by the same currency specifier.
    3. On the Met margin target line, replace the ____ with met_margin_target.

    You'll see a seven-line summary that starts with Weekly summary: Trail Water Bottle, includes Total cost: $1,140.00 and Profit: $1,858.80, and ends with Met revenue target: True and Met margin target: False. Congratulations on completing the lab.

    You turned four loose product values into a weekly profit report for the trail water bottle, one that shows the product beat its revenue target but missed its margin target. To get there, you diagnosed a TypeError caused by numbers stored as text, converted those values with float() and int(), and wrote the revenue, cost, profit, and margin calculations with arithmetic operators.

    You also practiced two skills you'll use in almost every analysis: comparing results against targets to get clear True or False answers, and presenting numbers with f-strings and format specifiers so that currency and percentages read the way people expect.

About the author

Pluralsight’s AI authoring technology is designed to accelerate the creation of hands-on, technical learning experiences. Serving as a first-pass content generator, it produces structured lab drafts aligned to learning objectives defined by Pluralsight’s Curriculum team. Each lab is then enhanced by our Content team, who configure the environments, refine instructions, and conduct rigorous technical and quality reviews. The result is a collaboration between artificial intelligence and human expertise, where AI supports scale and efficiency, and Pluralsight experts ensure accuracy, relevance, and instructional quality, helping learners build practical skills with confidence.

Real skill practice before real-world application

Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.

Learn by doing

Engage hands-on with the tools and technologies you’re learning. You pick the skill, we provide the credentials and environment.

Follow your guide

All labs have detailed instructions and objectives, guiding you through the learning process and ensuring you understand every step.

Turn time into mastery

On average, you retain 75% more of your learning if you take time to practice. Hands-on labs set you up for success to make those skills stick.

Get started with Pluralsight