- Lab
-
Libraries: If you want this lab, consider one of these libraries.
- Data
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 Info
Table of Contents
-
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_pricecan 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. Openproduct_margin_report.ipynbfrom the File Explorer, then run all of the code cells in this step by selecting each one in turn and pressingShift+Enter.info> Feeling stuck? Open
product_margin_report_solution.ipynbfrom 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 withNameError: name '____' is not defined, which means the blank still needs your code.The first code cell already assigns
product_nameandunit_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 exportComplete the two remaining assignments, then run the cell:
- Replace the
____afterunit_costwith the number9.50, typed without quotes. - Replace the
____afterunits_soldwith 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, and120. In this output,24.99and120look 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 atype()call onunits_sold, then run the cell.You'll see
<class 'str'>forproduct_name,unit_price, andunits_sold, and<class 'float'>forunit_cost.If
units_soldshows<class 'int'>instead, you typed120without 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. Afloatis 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. - Replace the
-
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_priceandunits_soldwill 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_soldThe cell stops with a
TypeErrorwhose last line readsTypeError: can't multiply sequence by non-int of type 'str'.Read an error message from the bottom up.
TypeErrornames 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 inunit_price, and'str'is the type ofunits_sold. The error stops only this cell, so you continue by running the next cell. The notebook tags this cellraises-exceptionso 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
intis allowed, and it repeats the text. The next cell multipliesunit_price, which is still a string, by3. There's nothing to type in it. Run it:unit_price * 3You'll see
'24.9924.9924.99', the price text written three times, and no error. Ifunits_soldhad been the integer120instead 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 withtype()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_priceneeds to become a decimal number, and the built-infloat()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 tofloat()onunit_price, then run the cell.The cell produces no output.
A count of items sold never has a fractional part, so
units_soldneeds to become a whole number, and the built-inint()function converts a value to one:units_sold = ____Replace the
____with a call toint()onunits_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'>forunit_priceand<class 'int'>forunits_sold, confirming that both conversions worked. -
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 = ____ revenueReplace the
____with an expression that multipliesunit_pricebyunits_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_costReplace the
____with an expression that multipliesunit_costbyunits_sold, then run the cell.You'll see
1140.0.Profit is what remains of revenue after costs:
profit = ____ profitReplace the
____with an expression that subtractstotal_costfromrevenue, 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_marginReplace the
____with an expression that dividesprofitbyrevenue, then run the cell.You'll see
0.6198479391756703, meaning about 62 cents of every dollar of revenue is profit. -
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
TrueorFalseanswers 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%. Becauseprofit_marginis stored as a decimal, the margin target is stored the same way, as0.65. The next cell stores both targets, and there's nothing to type in it. Run it:revenue_target = 2500.00 margin_target = 0.65The cell produces no output.
A comparison operator compares two values and produces a boolean, a value that is either
TrueorFalse. 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 inmet_revenue_target:met_revenue_target = ____ met_revenue_targetReplace the
____with a comparison that checks whetherrevenueis greater than or equal torevenue_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_targetReplace the
____with a comparison that checks whetherprofit_marginis greater than or equal tomargin_target, then run the cell.You'll see
False, because a margin of about 62% falls short of 65%. -
Challenge
Step 5: Report results with f-strings
Your calculations and target checks are complete, but raw output such as
2998.7999999999997and0.6198479391756703isn'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 letterfbefore the opening quote. Inside it, any variable name wrapped in curly braces is replaced with that variable's value, sof"Hello, {name}"becomesHello, Adawhennameholds"Ada". The next cell prints the report's heading:print(____)Replace the
____with an f-string that readsWeekly summary:followed byproduct_namein 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
:,.2fadds 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
____withrevenuefollowed by the:,.2fspecifier, 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
____withprofit_marginfollowed 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:
- On the
Total costline, replace the____withtotal_costfollowed by the same currency specifier you used for revenue. - On the
Profitline, replace the____withprofitfollowed by the same currency specifier. - On the
Met margin targetline, replace the____withmet_margin_target.
You'll see a seven-line summary that starts with
Weekly summary: Trail Water Bottle, includesTotal cost: $1,140.00andProfit: $1,858.80, and ends withMet revenue target: TrueandMet 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
TypeErrorcaused by numbers stored as text, converted those values withfloat()andint(), 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
TrueorFalseanswers, and presenting numbers with f-strings and format specifiers so that currency and percentages read the way people expect. - On the
About the author
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.