Lesson 2 - Variables and Data Types
Building on Your Knowledge of Python Data Handling
In this lesson, we’ll learn how to store values and work with both numerical and text data in Python. Knowing how to manage numbers and strings sets the groundwork for more advanced tasks, including data analytics and machine learning models. Before starting, it’s best if you already know how to write basic Python code and perform simple arithmetic operations.
We’ll begin by showing how to store the result of a calculation in a variable. For example, let’s consider the arithmetic expression (4 + 6) * 3
. The result of this calculation is 30
, and we can assign that value to a variable for later use.
Output:
Alternatively, we can let Python do the math first and then store the outcome directly:
Output:
When we run print(final_value)
, we see 30
because Python calculates (4 + 6) * 3
first, then stores 30
inside final_value
.
Let’s start with a quick exercise before moving on to explore variables in greater depth.
Exercise:
- Compute
(50 - 8) * 4
and store the result in a variable namedcalc_result
. - Print the value of
calc_result
.
Understanding Variables
When we write something like:
We instruct Python to place the number 30
into a specific storage spot in the computer’s memory. Think of the computer’s memory as a huge grid of tiny storage boxes, each capable of holding a piece of information. By writing record_count = 30
, we label one of these boxes with the name record_count
and store 30
there.
Concept Illustration: Imagine a large grid of storage locations (memory). Each spot can hold a piece of data. By assigning a value to a variable name, we place data in one of these spots and give it a recognizable label.
Once record_count
holds 30
, we can use it anywhere in our code:
Output:
The variable record_count
serves as a handle to the value 30
. When you run record_count + 10
, Python fetches 30
from memory and computes 30 + 10 = 40
.
You can choose any valid name for a variable:
Output:
Exercise:
- Assign
12
to a variable callednum_value
. - Compute
(33 - 5) * 9
and store it in a variable namedcalc_result
. - Print the following:
- The value of
num_value
. - The result of
calc_result + 15
. - The sum of
num_value
andcalc_result
.
- The value of
Naming Your Variables
Variable names must follow certain rules. For example, you can’t write:
This will cause a syntax error because spaces aren’t allowed in variable names.
Rules for Variable Names:
- Use only letters, digits, or underscores (
_
). - Don’t start the name with a digit.
Variable names are case sensitive. This means dataCount
and DataCount
would be considered different variables.
Valid and Invalid Variable Names:
Valid Names | Invalid Names | Reason Invalid |
---|---|---|
data_set_2024 | 1_value | Starts with a digit |
Sales_Summary | new data | Contains a space |
weekly_Stats | item’s_price | Contains an apostrophe |
Output_Results | old-value | Contains a hyphen |
_tempVar | cost_in_$ | Contains a $ character |
Exercise: In the code editor, these two lines are currently commented out:
- Change
old-profit
toold_profit
. - Change
new profit
tonew_profit
. - Remove the
#
so the code runs without errors.
Changing Stored Values
We can update the value of a variable after we create it. For example:
Output:
We can also update a variable using arithmetic:
Output:
Exercise:
- Suppose a variable named
income
is already defined in the code editor. - Increase
income
by5000
usingincome = income + 5000
. - Print
income
.
Shortcut Operators
Instead of writing x = x + 10
, Python lets us use x += 10
:
Output:
Below is a table of shortcut operators you can use:
Shortcut | Example Code | Resulting Value |
---|---|---|
+= | a = 5 a += 3 | a becomes 8 |
-= | b = 10 b -= 2 | b becomes 8 |
*= | c = 4 c *= 2 | c becomes 8 |
/= | d = 16 d /= 4 | d becomes 4.0 |
**= | e = 3 e **= 3 | e becomes 27 |
If you try using these shortcuts on a variable that hasn’t been defined, you get a NameError
. This is a runtime error (the code is syntactically correct, but logically it cannot proceed because the variable doesn’t exist yet).
Also note, the =
operator in programming is not the same as the equals sign in mathematics. In Python, =
means “assign the value on the right to the variable on the left.”
Exercise:
- Assign
10
to a variable namedvar_one
. - Assign
2.5
to a variable namedvar_two
. - Increase
var_two
by5
using the+=
shortcut. - Multiply
var_one
by3
using the*=
shortcut. - Print both
var_one
andvar_two
.
Working with Integers and Floats
Integers (int
) are whole numbers like 2
, -5
, 100
. Floats (float
) are numbers with decimal parts like 3.7
or -0.1
.
Output:
Both int
and float
are numeric types and can be mixed in arithmetic operations.
Exercise:
- Assign the integer
8
to a variable namednum_a
. - Assign the float
3.4
to a variable namednum_b
. - Add
2.6
tonum_a
(use+=
). - Multiply
num_b
by2
(use*=
). - Print
num_a
andnum_b
.
Converting Between Number Types
We can convert integers to floats and vice versa:
Output:
For more flexible rounding, use round()
:
Changing a variable’s value requires re-assignment:
Exercise:
- Assign
14.7
tovar_x
. - Assign
2.4
tovar_y
. - Round
var_x
and store the result back intovar_x
. - Convert
var_y
to an integer and store it back intovar_y
. - Print
var_x
andvar_y
.
Introducing Strings
Besides numbers, we often work with text in data analytics. Consider a dataset of apps:
app_name | price | currency | total_reviews | avg_rating |
---|---|---|---|---|
ChatterBox | 0.0 | USD | 2,300,145 | 4.2 |
SnapFeed | 0.0 | USD | 1,987,000 | 4.3 |
BattleLand | 0.0 | USD | 2,150,900 | 4.5 |
RunSquare | 0.0 | USD | 1,500,345 | 4.1 |
MusicCloud | 0.0 | USD | 1,250,678 | 4.0 |
Text data like ChatterBox
or USD
is represented as a string (str
). We create strings by putting characters between quotes:
Output:
We can use single or double quotes, but not both at once to define one string.
Output:
Strings can contain letters, numbers, spaces, and symbols:
Exercise:
- Assign
"MusicCloud"
toapp_identity
. - Assign
"4.0"
torating_str
(note that this is a string, not a float). - Assign
"1250678"
toreviews_str
(a string, not an int). - Assign
"free"
tocost_status
. - Print
app_identity
.
Escaping Special Characters
What if we need to use quotes inside a string?
Output:
Here we used double quotes on the outside and single quotes inside. If we want to mix quotes more freely, we can use a backslash \
to escape characters that would otherwise end the string:
Output:
The backslash \
tells Python that the following character doesn’t end the string.
Exercise:
Assign the string Meta's AI slogan is "Go. Innovate. Achieve.".
to a variable named tagline
and then print it. Remember to handle the apostrophe in Meta's
and the quotes around "Go. Innovate. Achieve."
.
String Operations
Strings can be combined (concatenated) using +
:
Output:
We can also repeat strings using *
:
Output:
Note that '4' + 1
will cause an error because you can’t add a string directly to a number. You must convert the string '4'
to an integer or float first:
Output:
We can also turn numbers into strings:
Output:
For multi-line strings, use triple quotes:
Output:
Exercise:
- Assign
Platform's average rating is
toplatform_msg
. - Assign
3.7
(a float) toplatform_rating
. - Convert
platform_rating
to a string and store it inplatform_rating_str
. - Concatenate
platform_msg
with a space andplatform_rating_str
. - Print the final result.
Looking Ahead
In this lesson, we covered:
- How to store values in variables.
- How to work with integers and floats.
- How to handle text data (strings).
- How to convert between different data types.
In the next lessons, we’ll explore more advanced programming concepts while examining even larger datasets with many rows and columns. Mastering variables, data types, and conversions now will prepare you for more complex data operations and analytics tasks ahead.