🚧 Under construction — VoTechWorks is being built. A free tech program — complimentary, as our commitment to get America working.
voTechWorksGrade 13 · a vocational technology learning center, by urbanicity
newSchoolWorks.com › VoTechWorks › Technology & Design › Data Science & Analytics › Python and R for Data Science & Analytics › Lesson 2
TEC-DATA85-03 · Lesson 2 · 12 clock hours · theory

Python Syntax, Variables, and Core Data Structures

Objective. Students write Python code that correctly uses variables, numeric and string types, lists, tuples, and dictionaries to store and retrieve data values.

⚠ Pending professional review

This lesson, its worked examples and its practice questions has not yet been verified by an industry-certified professional or by a certification or approval body. It is a study draft and may contain errors. Do not use it as instructions for work on a job site or on live equipment. Always follow your instructor, your supervising professional, and current official references and regulations.

VoTechWorks program approval and accreditation are still in progress. Credentials are issued only by the certifying bodies named in each program, after their own exams.

What Is Python and Why Does It Matter in Data Science?

Python is an interpreted, general-purpose programming language that has become the dominant tool in data science and analytics. Its readable syntax, large standard library, and rich ecosystem of data-focused packages — including pandas, NumPy, and Matplotlib — make it practical for everything from quick data cleaning to building machine learning models. Google Data Analytics and CompTIA Data+ both expect candidates to understand how Python stores and manipulates data, so mastering the fundamentals in this lesson directly supports your certification goals.

All work in this lesson takes place inside Jupyter Notebook, a browser-based environment that lets you run code one cell at a time and see output immediately. Before running any cell, always predict what the output will be and record it in your lab log. Comparing your prediction to the actual output is the single fastest way to find gaps in your mental model.

Variables and Assignment

A variable is a named container that holds a value. In Python you create a variable the moment you assign a value to it — there is no separate declaration step.

```python

city = "Denver"

population = 715522

growth_rate = 1.37

is_capital = False

```

The name on the left receives the value on the right. Python is case-sensitive, so `City` and `city` are two different variables. Follow PEP 8 naming conventions: use lowercase letters and underscores for variable names (`growth_rate`, not `GrowthRate`).

Core Data Types

Python tracks the type of every value automatically. The four scalar (single-value) types you will use constantly are:

Use the built-in function `type()` to inspect any value: `type(1.37)` returns `<class 'float'>`. Use `int()`, `float()`, and `str()` to convert between types when needed — for example, reading a CSV often delivers numbers as strings that must be cast to `int` or `float` before arithmetic.

Lists

A list is an ordered, mutable (changeable) sequence of values enclosed in square brackets.

```python

populations = [715522, 2161000, 897000, 305704]

```

Key operations:

Lists can hold mixed types, but in data work it is best practice to keep one type per list to avoid unexpected errors during calculations.

Tuples

A tuple is an ordered, immutable (unchangeable) sequence enclosed in parentheses.

```python

coordinates = (39.7392, -104.9903)

```

Because tuples cannot be altered after creation, they are ideal for fixed data like geographic coordinates, RGB color codes, or column header definitions. Indexing and slicing work the same way as with lists. Attempting to assign a new value to a tuple index raises a `TypeError`.

Dictionaries

A dictionary stores data as key-value pairs enclosed in curly braces. Keys must be unique and are usually strings or integers.

```python

sensor_readings = {

"temperature_c": 22.4,

"humidity_pct": 58.1,

"co2_ppm": 412

}

```

Key operations:

Dictionaries are the backbone of many data pipelines because they map field names to values, mirroring the structure of JSON records and database rows.

PEP 8 and Code Safety

PEP 8 is the official Python style guide. Following it makes your code readable to colleagues and reduces errors:

In a data environment, poorly named variables and missing comments are a form of data integrity risk — the next analyst may misread your intent and introduce errors. Always add a comment explaining your approach, especially when indexing or slicing.

While this lesson involves no physical hazards, never run unknown code on production data systems. Always develop and test in an isolated environment such as a local Jupyter instance or a sandboxed cloud notebook. Back up your work to the shared repository regularly using descriptive commit messages so changes are traceable.

Checking Your Work

Before submitting your notebook:

1. Restart the kernel and run all cells top to bottom — this catches errors caused by running cells out of order.

2. Confirm each exercise cell produces the expected output.

3. Verify every exercise includes a comment (`# ...`) explaining the approach.

4. Run a quick PEP 8 check using your notebook's linting tool or the `pycodestyle` package.

Submit the corrected notebook to the shared repository with a commit message that describes what you changed, for example: `Fix indexing error in exercise 7; add PEP 8 spacing`.

Key terms8

VariableA named storage location in memory that holds a value; created in Python by assignment using the = operator.
Data typeThe classification of a value that determines what operations can be performed on it; common Python types include int, float, str, and bool.
ListAn ordered, mutable sequence of values enclosed in square brackets; supports indexing, slicing, and in-place modification.
TupleAn ordered, immutable sequence of values enclosed in parentheses; used for fixed data that should not change after creation.
DictionaryA mutable collection of key-value pairs enclosed in curly braces; keys must be unique and are used to retrieve their associated values.
IndexAn integer position used to access a single element in a sequence; Python uses zero-based indexing, so the first element is at position 0.
SliceA notation using a colon inside square brackets (e.g., list[1:4]) that returns a subset of a sequence; the start index is included and the end index is excluded.
PEP 8The official Python style guide that specifies conventions for naming, indentation, line length, and spacing to improve code readability and consistency.

Worked examples4

1. Create a list of five city population values, then retrieve the third city's population and calculate what percentage it represents of the total population across all five cities. Populations: 715522, 2161000, 897000, 305704, 460000.
  1. Define the list: populations = [715522, 2161000, 897000, 305704, 460000]
  2. Retrieve the third element using zero-based index 2: third_city = populations[2] — this gives 897000.
  3. Calculate the total using the built-in sum() function: total = sum(populations) — 715522 + 2161000 + 897000 + 305704 + 460000 = 4539226.
  4. Calculate the percentage: pct = (third_city / total) * 100 — (897000 / 4539226) * 100 = 19.76 (rounded to two decimal places).
  5. Print the result: print(round(pct, 2)) outputs 19.76.
Answer: The third city's population (897000) is approximately 19.76% of the combined total (4539226).
2. A dictionary stores three sensor readings: temperature_c = 22.4, humidity_pct = 58.1, co2_ppm = 412. Add a new key pressure_hpa with value 1013.2, then print all keys and confirm the dictionary now has four entries.
  1. Define the dictionary: sensor_readings = {"temperature_c": 22.4, "humidity_pct": 58.1, "co2_ppm": 412}
  2. Add the new key-value pair: sensor_readings["pressure_hpa"] = 1013.2
  3. Print all keys: print(list(sensor_readings.keys())) outputs ['temperature_c', 'humidity_pct', 'co2_ppm', 'pressure_hpa']
  4. Confirm the count: print(len(sensor_readings)) outputs 4.
Answer: After adding 'pressure_hpa', the dictionary contains four key-value pairs. len(sensor_readings) returns 4.
3. Given the list temps = [15.2, 18.7, 21.0, 19.4, 16.8], use slicing to extract the middle three values, then compute their average.
  1. Define the list: temps = [15.2, 18.7, 21.0, 19.4, 16.8]
  2. Slice the middle three elements (indices 1 through 3 inclusive): middle = temps[1:4] — this returns [18.7, 21.0, 19.4].
  3. Calculate the sum of the slice: sum(middle) = 18.7 + 21.0 + 19.4 = 59.1
  4. Divide by the number of elements: average = 59.1 / 3 = 19.7
  5. Print: print(average) outputs 19.7.
Answer: The average of the middle three temperature values [18.7, 21.0, 19.4] is 19.7.
4. You have the tuple coordinates = (39.7392, -104.9903) representing latitude and longitude. Attempt to update the latitude to 40.0 and explain what happens.
  1. Define the tuple: coordinates = (39.7392, -104.9903)
  2. Attempt assignment: coordinates[0] = 40.0
  3. Python raises a TypeError: 'tuple' object does not support item assignment — tuples are immutable.
  4. To store a corrected coordinate pair, create a new tuple: coordinates = (40.0, -104.9903)
  5. The original tuple is discarded and the variable now points to the new tuple; no in-place modification occurred.
Answer: Attempting to modify a tuple index raises a TypeError. The correct approach is to create a new tuple and reassign the variable.

The math in this lesson1

Learners compute totals and percent shares from a Python list of city populations.
7.RP.3
Brush up in the math halls at newSchoolWorks.com:
In class: Work through an annotated code walkthrough distinguishing int, float, str, bool, list, tuple, and dict; predict output before running each cell in Jupyter and record mismatches in the lab log. · Complete 15 structured exercises (provided as a Jupyter notebook) that require creating, indexing, slicing, and updating lists and dictionaries representing small datasets (e.g., a list of city population values, a dictionary of sensor readings). · Pair with a classmate to peer-review each other's solutions, identify at least one bug or style issue using PEP 8 guidelines, and push the corrected notebook to the shared repository with a descriptive commit message.
Materials: Jupyter Notebook, Python 3.x documentation (docs.python.org), PEP 8 style guide, exercise notebook provided by instructor, shared repository
Check: Instructor reviews submitted notebook; 12 of 15 exercises must produce correct output and include a comment explaining the approach — maps to Google Data Analytics and CompTIA Data+ programming knowledge domains.

Practice check8

Answer each question, then check it. Nothing is recorded; this is your own practice.

Google Data Analytics — programming fundamentals
1. Which Python data type is best suited for storing a fixed pair of GPS coordinates that should never be modified after creation?
CompTIA Data+ — data types and data structures
2. A Python list named scores = [88, 92, 75, 100, 63] is defined. What does scores[1:4] return?
CompTIA Data+ — data types
3. What is the output of type(3.0) in Python?
Google Data Analytics — programming best practices
4. A student writes the variable name SensorTemp instead of sensor_temp. Which coding standard does this violate?
Google Data Analytics — data structures
5. Given sensor_data = {"co2": 412, "temp": 22.4}, which statement correctly adds a new key "humidity" with value 58.1?
Google Data Analytics — programming workflow
6. A student runs cells in a Jupyter Notebook out of order and gets a NameError. What is the recommended fix before submitting the notebook?
CompTIA Data+ — data types and conversion
7. Which of the following correctly converts the string "2024" to an integer so it can be used in arithmetic?
CompTIA Data+ — data structures
8. A list named readings = [10, 20, 30, 40, 50] is defined. After executing readings[-1], what value is returned?
Record this lesson on my transcript. Sign in with your key and enrollment email to record lessons (enroll free if you have no key). This page stays open to read and practise.