Module 2 · Python for Data · Lesson 4 of 51

Values, variables, numbers and text

Variables, the core types (int, float, str, bool), arithmetic, rounding, string methods and f-strings for clean reports.

In this lesson · about 35 minutes

  • Store values in variables and do arithmetic, including //, % and **
  • Tell int, float, str and bool apart, and convert between them
  • Clean and format text with string methods and f-strings

The four basic types

TypeExamplesUsed for
int3, -12, 4420Counts
float4.5, 0.118Measurements, money, rates
str"Latte", 'Airport'Text and labels
boolTrue, FalseYes/no answers, filters

type(x) tells you what you have. Convert with int("3"), float("4.50"), str(12). Data from files often arrives as text, so converting is a daily task.

Arithmetic

+ - * / as usual; ** is power (2 ** 3 is 8); // divides and drops the remainder (17 // 5 is 3); % gives the remainder (17 % 5 is 2). round(3.14159, 2) gives 3.14. Comparisons (==, !=, <, >=) give a bool.

Text

Strings have methods, tools attached with a dot: .strip() removes spaces at both ends, .lower(), .upper() and .title() change case, .replace("a", "b") swaps text, .split(",") breaks a line into a list, and "Air" in "Airport" checks whether one text contains another. These are exactly the tools for cleaning messy branch names.

An f-string drops values into text: f"Revenue: ${revenue:,.2f}" prints Revenue: $1,989.00. Inside the braces, :,.2f means "commas for thousands, 2 decimal places", and :.1% shows 0.118 as 11.8%.

Numbers and types

Cleaning text and f-strings

Exercise

Profit margin

A latte sells for 4.50 and costs 1.35 to make. Set margin to the profit as a share of the price (profit ÷ price), and label to an f-string that reads exactly Margin: 70.0%.

Exercise

Clean a branch name

The till exported raw = " RIVERSIDE ". Set clean to "Riverside" using string methods (don't type the answer in yourself).

Check your understanding0 of 4 correct

Question 1

1.What is 17 // 5?

Question 2

2.What does ' Latte '.strip() return?

Question 3

3.How does f"{0.257:.1%}" display?

Question 4

4.The value "12" read from a file is a…

Quiz score: 0 of 4

Exercises solved: 0 of 2

Tip: answer every quiz question correctly first.

Written by Noviq Academy in its own words. Kettle & Crumb and all its data are made up for teaching; any resemblance to a real business is a coincidence. Python runs in your browser with Pyodide, so results can differ slightly from your own computer. Power BI, Tableau and other product names belong to their owners. Read-aloud uses your device's built-in voices.