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.

final_value = 30
print(final_value)

Output:

30

Alternatively, we can let Python do the math first and then store the outcome directly:

final_value = (4 + 6) * 3
print(final_value)

Output:

30

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:

  1. Compute (50 - 8) * 4 and store the result in a variable named calc_result.
  2. Print the value of calc_result.

Understanding Variables

When we write something like:

record_count = 30

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:

record_count = 30
print(record_count)
print(record_count + 10)

Output:

30
40

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:

my_number = 30
print(my_number)
print(my_number + 10)

Output:

30
40

Exercise:

  1. Assign 12 to a variable called num_value.
  2. Compute (33 - 5) * 9 and store it in a variable named calc_result.
  3. Print the following:
    • The value of num_value.
    • The result of calc_result + 15.
    • The sum of num_value and calc_result.

Naming Your Variables

Variable names must follow certain rules. For example, you can’t write:

my total = 100

This will cause a syntax error because spaces aren’t allowed in variable names.

Rules for Variable Names:

  1. Use only letters, digits, or underscores (_).
  2. 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 NamesInvalid NamesReason Invalid
data_set_20241_valueStarts with a digit
Sales_Summarynew dataContains a space
weekly_Statsitem’s_priceContains an apostrophe
Output_Resultsold-valueContains a hyphen
_tempVarcost_in_$Contains a $ character

Exercise: In the code editor, these two lines are currently commented out:

# old-profit = 34000
# new profit = 40000
  1. Change old-profit to old_profit.
  2. Change new profit to new_profit.
  3. 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:

count = 25
print(count)
count = 60
print(count)

Output:

25
60

We can also update a variable using arithmetic:

count = 25
print(count)      # Shows 25
print(count + 15) # Shows 40 (but does not update count itself)
count = count + 15
print(count)      # Now count is truly updated to 40

Output:

25
40
40

Exercise:

  1. Suppose a variable named income is already defined in the code editor.
  2. Increase income by 5000 using income = income + 5000.
  3. Print income.

Shortcut Operators

Instead of writing x = x + 10, Python lets us use x += 10:

x = 20
x += 10
print(x)

Output:

30

Below is a table of shortcut operators you can use:

ShortcutExample CodeResulting 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:

  1. Assign 10 to a variable named var_one.
  2. Assign 2.5 to a variable named var_two.
  3. Increase var_two by 5 using the += shortcut.
  4. Multiply var_one by 3 using the *= shortcut.
  5. Print both var_one and var_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.

print(4 + 1.2)
print(type(4))
print(type(1.2))

Output:

5.2
<class 'int'>
<class 'float'>

Both int and float are numeric types and can be mixed in arithmetic operations.

Exercise:

  1. Assign the integer 8 to a variable named num_a.
  2. Assign the float 3.4 to a variable named num_b.
  3. Add 2.6 to num_a (use +=).
  4. Multiply num_b by 2 (use *=).
  5. Print num_a and num_b.

Converting Between Number Types

We can convert integers to floats and vice versa:

print(float(7))   # Converts 7 to 7.0
print(int(9.9))   # Converts 9.9 to 9 (rounds down)

Output:

7.0
9

For more flexible rounding, use round():

print(round(9.9))  # rounds to 10
print(round(9.5))  # might round to 10 depending on Python's rounding strategy

Changing a variable’s value requires re-assignment:

val = 3.8
print(round(val)) # Shows 4, but val is still 3.8
print(val)         # Still 3.8
val = round(val)   # Now val is truly 4
print(val)         # Shows 4

Exercise:

  1. Assign 14.7 to var_x.
  2. Assign 2.4 to var_y.
  3. Round var_x and store the result back into var_x.
  4. Convert var_y to an integer and store it back into var_y.
  5. Print var_x and var_y.

Introducing Strings

Besides numbers, we often work with text in data analytics. Consider a dataset of apps:

app_namepricecurrencytotal_reviewsavg_rating
ChatterBox0.0USD2,300,1454.2
SnapFeed0.0USD1,987,0004.3
BattleLand0.0USD2,150,9004.5
RunSquare0.0USD1,500,3454.1
MusicCloud0.0USD1,250,6784.0

Text data like ChatterBox or USD is represented as a string (str). We create strings by putting characters between quotes:

app_title = "ChatterBox"
currency_code = "USD"
print(app_title)
print(currency_code)

Output:

ChatterBox
USD

We can use single or double quotes, but not both at once to define one string.

app_one = "SnapFeed"
app_two = 'SnapFeed'
print(app_one, app_two)

Output:

SnapFeed SnapFeed

Strings can contain letters, numbers, spaces, and symbols:

description = "BattleLand is free with an average rating of 4.5"
print(description)

Exercise:

  1. Assign "MusicCloud" to app_identity.
  2. Assign "4.0" to rating_str (note that this is a string, not a float).
  3. Assign "1250678" to reviews_str (a string, not an int).
  4. Assign "free" to cost_status.
  5. Print app_identity.

Escaping Special Characters

What if we need to use quotes inside a string?

note = "The CEO said, 'We value creativity.'"
print(note)

Output:

The CEO said, 'We value creativity.'

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:

message = 'Our slogan is "Think \& Create".'
print(message)

Output:

Our slogan is "Think & Create".

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 +:

print('Hello' + 'World')
print('Hello' + ' ' + 'World')

Output:

HelloWorld
Hello World

We can also repeat strings using *:

print('Hi!' * 3)

Output:

Hi!Hi!Hi!

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:

print(int('4') + 1)

Output:

5

We can also turn numbers into strings:

print(str(4))

Output:

4

For multi-line strings, use triple quotes:

text_block = """Line one
Line two
'Quotes' inside are fine here."""
print(text_block)

Output:

Line one
Line two
'Quotes' inside are fine here.

Exercise:

  1. Assign Platform's average rating is to platform_msg.
  2. Assign 3.7 (a float) to platform_rating.
  3. Convert platform_rating to a string and store it in platform_rating_str.
  4. Concatenate platform_msg with a space and platform_rating_str.
  5. 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.