Data Analysis with Python
Data Analysis with Python
What Data Analysis Does
Data analysis is the process of inspecting, cleaning, transforming, and modeling data to discover useful information, draw conclusions, and support decision-making. Its purpose is not merely to calculate statistics: it is to turn raw data into information that people can use.
For example, a retailer might collect a year of purchase records. The raw data is a large collection of transactions; an analysis might reveal that a particular product sells better on Tuesdays. That finding is useful only if it is communicated clearly and supported by evidence.
A typical analysis therefore involves several connected activities:
Gathering data from sources such as databases, files, or web APIs.
Checking its structure and quality.
Cleaning errors and handling missing or invalid values.
Reshaping or combining data so it can answer a particular question.
Applying statistical analysis and visualizations to identify patterns, trends, or anomalies.
Communicating findings through reports, dashboards, or other outputs.
The people using those outputs may include marketing, sales, accounting, executives, or other departments. Different audiences may need different levels of detail or different views of the same underlying information.
Data-Analysis Tools
Data-analysis tools can be understood broadly as managed products and open programming tools.
Managed products
Products such as spreadsheets and business-intelligence tools are generally ready to use and may provide visual, point-and-click workflows. They can be relatively easy to learn, and a vendor may provide documentation, support, and ongoing development.
Their main limitation is scope: an analyst may be restricted by the features or boundaries of the product. They can also become slow or awkward when the data grows beyond what is practical to explore visually.
Programming tools
Programming-based analysis combines a language with libraries and other open tools. Common languages include Python, R, and Julia. A programming language can work with specialized data sources, APIs, authentication methods, cloud services, and workflows that a packaged product may not support directly.
Programming also makes analysis more transferable. A process can be saved, repeated, reviewed, and moved between computers or computing environments with less manual work. The trade-off is that analysts must learn programming fundamentals, which takes time.
Why Python?
Python is widely used because it is readable, versatile, and supported by a large ecosystem of libraries. It can be used for data processing, visualization, web development, automation, machine learning, and many other tasks. It is free and open source, has extensive documentation, and is used by organizations across many industries.
Python also has a large community, which contributes libraries, tutorials, and other learning resources. Its broad usefulness can make programming skills valuable beyond any single data-analysis product.
R is another strong choice, particularly in statistically intensive fields. It has extensive statistical functionality. Python is often preferred by new programmers because it is relatively approachable and has a broad range of general-purpose libraries.
Data analysis and data science
The boundary between data analysis and data science is not precise, and the work often overlaps.
Data analysts often emphasize interpreting results, communicating findings, producing reports, and using storytelling to help others act on evidence.
Data scientists may place greater emphasis on programming, mathematics, machine learning, and complex data-engineering processes such as ETL (extract, transform, load).
The appropriate distinction depends on the organization and the project.
The Data-Analysis Workflow
A common workflow has five broad stages. In practice, it is cyclical rather than strictly linear: results from one stage may reveal a problem or a new question that sends the analyst back to an earlier stage.
1. Obtain data
Data may come from an organization’s database, a CSV or Excel file, a web API, or another source. Understanding where the data comes from is important because the source affects its structure, reliability, and the amount of cleaning it may require.
2. Clean the data
Cleaning addresses problems such as missing values, invalid entries, inconsistent formats, and errors. Data from a well-maintained internal database may require relatively little repair; data gathered through less controlled processes may require much more.
3. Transform and reshape the data
Data often needs to be rearranged before it can answer a question. This may involve:
Changing the shape or format of fields.
Creating new columns from existing ones.
Merging tables.
Combining data from multiple sources.
Filtering to a relevant subset.
The goal is to prepare a usable representation for analysis.
4. Analyze the data
Analysis looks for patterns, trends, relationships, and anomalies in the prepared data. Statistical methods and visualizations help reveal what may not be obvious from a raw table.
5. Communicate or act on the findings
The final step depends on the project. A data-analysis project may produce a report or dashboard that supports a decision. A broader data-science project may proceed to machine-learning models or other automated systems. In either case, findings should be communicated in a form that the intended audience can understand.
Working with Large Data
Traditional spreadsheet and dashboard workflows often give analysts a constant visual reference: rows and columns are directly visible, and users interact with them through menus or clicks. This is useful for small datasets but does not scale well. As the number of records grows, it becomes difficult for a person to inspect everything, and some visual tools may become slow.
Programming encourages a different approach. Analysts use a compact set of structural and statistical summaries to maintain an understanding of the data without examining every row. Useful references include:
Number of rows and columns.
Column names and data types.
Counts of missing or present values.
A small sample of the first or last rows.
Summary statistics such as the mean, median, minimum, maximum, and standard deviation.
Plots that show distributions, relationships, or unusual values.
This approach can be applied to datasets with very large numbers of records. It also makes it easier to move a repeatable analysis from one computer to another, including to a cloud environment.
A Typical Analysis in Python
A sales-analysis workflow illustrates how the tools fit together.
Inspecting a CSV dataset
A CSV file can be loaded into a pandas DataFrame, a structured, table-like data object. After loading it, an analyst can check:
Its shape: how many rows and columns it contains.
Its columns and their data types.
Whether any columns contain missing values.
Summary statistics for numeric fields.
For a customer-sales dataset, the columns might include a date, customer age, age group, gender, unit cost, order quantity, revenue, and profit. A summary may show, for example, the average and range of customer ages. That information can help the analyst notice a suspicious value, such as an unexpectedly high age or a negative profit that needs investigation.
The aim is not to read every row. It is to build a high-level understanding of the dataset and use that understanding to guide the next steps.
Exploring distributions and relationships
Several common analyses can be performed on the same dataset:
Box plots summarize a distribution using quartiles and a median, and can help reveal potential outliers.
Histograms show how values are distributed across ranges.
Density plots provide a smoothed view of a distribution.
Value counts show how often categories occur; they can support bar charts or pie charts.
Correlation matrices summarize the direction and strength of relationships among numeric variables. The diagonal entries represent each variable’s correlation with itself, which is 1.
Scatter plots show the relationship between two numeric variables.
Grouped box plots can compare a measure, such as profit, across categories such as customer age groups.
A relationship in a plot or correlation matrix is a prompt for further analysis, not proof that one variable causes another.
Creating and validating fields
Python can create new columns from existing ones. For example, an analyst can calculate a revenue-per-customer measure, or estimate total cost as order quantity multiplied by unit cost. These calculated values can then be compared with values already supplied in the dataset.
Such comparisons can help identify data-entry or system errors. If a calculated total differs from the stored total, the discrepancy should be investigated rather than automatically assumed to be an error.
Filtering and changing values
Data can be filtered by location, customer group, product, or other fields. An analyst might isolate sales from a particular state or calculate average revenue for a selected group.
A transformation can also update values according to a rule, such as applying a price increase. Such changes are examples of what code can do; actual analytical changes should be based on a clearly stated purpose rather than applied arbitrarily.
Reading from a database
The analysis steps are much the same when data comes from a SQL database. A SQL query retrieves selected records, and the results can be loaded into a DataFrame. Once the data is in that structure, the analyst can inspect, clean, transform, and visualize it using the same general workflow.
Jupyter Notebooks
Jupyter is an open-source ecosystem for interactive computing. Jupyter Notebook provides an interactive document in which code, explanatory text, and outputs can be combined. JupyterLab is a broader interface built around notebook work and includes features such as file browsing, terminals, and previews.
Cells and notebook contents
A notebook is made up of cells. A cell can contain executable code or Markdown text.
A code cell runs code in a language such as Python and displays its output.
A Markdown cell contains formatted text, such as headings, emphasis, lists, links, and images.
A raw cell is also available, although it is used less often in typical analysis work.
This combination makes a notebook useful for both exploration and explanation. A completed notebook can serve as a record of the analysis and can often be exported to formats such as HTML or PDF.
Execution and state
When a code cell runs, Jupyter assigns it an execution number. That number indicates the order in which the cell was executed, even if the cell is later moved. As a result, the visual top-to-bottom order of cells does not necessarily match the order in which the current results were produced.
This matters because a notebook maintains a live Python state. If a cell depends on a variable created by another cell, the result depends on whether the earlier cell has been run and on its current contents. Running cells from the beginning in order is a useful way to check that a notebook is reproducible.
Editing and command modes
The classic notebook interface has two modes:
Edit mode is used to type or modify the contents of a cell.
Command mode is used for actions on cells, such as adding, deleting, or moving them.
Pressing Enter enters edit mode; pressing Escape returns to command mode. In command mode, common shortcuts include:
A to add a cell above and B to add one below.
D twice to delete the selected cell.
Z to undo a cell action.
X to cut, C to copy, and V to paste a cell.
M to change a cell to Markdown and Y to change it to code.
Up and down arrows to navigate between cells.
For execution, Ctrl+Enter runs the current cell while keeping it selected. Shift+Enter runs it and moves to the next cell. A command palette or toolbar can also be used to find and run commands.
Why notebooks suit exploratory analysis
A notebook behaves like an interactive Python environment: code can be entered and its result inspected immediately. It also supports visual output. Libraries such as Matplotlib can display charts directly in notebook output, avoiding the need to use a separate chart-viewing process during exploration.
Notebooks can also work alongside files and other tools in the Jupyter environment. The specific ability to preview or work with particular file types depends on the installed extensions and software.
NumPy: Efficient Numerical Computing
NumPy is a foundational Python library for numerical computing. Its central data structure is the multidimensional array. Libraries such as pandas and Matplotlib rely on NumPy for many numerical operations.
Why numerical arrays matter
Python’s ordinary numeric objects and lists are flexible, but that flexibility can have costs when working with large volumes of numbers. A regular Python list can hold objects of different types, and its elements are not necessarily stored as a single uniform block of numeric data.
A NumPy array, by contrast, normally stores values of a consistent type in a compact, efficient representation. This enables fast operations on whole arrays and can reduce memory use.
A standard Python integer can use substantially more memory than the numeric value alone would require because it is represented as a Python object with associated information. NumPy supports fixed-width numeric types, such as integers of specified bit widths. Selecting a suitable type can be important when storing very large datasets, although many analyses can begin with NumPy’s default types.
Bits and fixed-width integers
Computers represent data in binary, using bits that take the values 0 or 1. With n bits, there are 2n possible bit patterns. For an unsigned integer, those patterns represent values from 0 through 2n−1.
For example, an unsigned 7-bit value can represent values from 0 through 127. A type must be wide enough to store the values that may occur. Age and net worth may both be represented as integers, but their possible ranges are very different, so they may have different storage requirements.
Fixed-width types require care: if a value exceeds the representable range, it cannot be safely stored in that type. Signed integers also use some of their bit patterns to represent negative values, so their range differs from an unsigned type of the same width. Floating-point numbers have their own representation and precision limits.
Creating and indexing arrays
A one-dimensional NumPy array is similar in appearance to a Python list, and both use zero-based indexing. An array can be selected by position, sliced, or indexed with a list of positions. Selecting several positions produces another array.
NumPy arrays can also be multidimensional:
A one-dimensional array is a sequence.
A two-dimensional array is commonly treated as a matrix with rows and columns.
A three-dimensional array can be visualized as a stack or block of matrices.
Useful array properties include:
Shape: the size of the array along each dimension.
Number of dimensions: how many axes the array has.
Size: the total number of elements.
For example, an array with shape (2,3) has two rows and three columns, for a total of 6 elements. Multidimensional arrays need consistent dimensions; irregular nested sequences may not form the intended rectangular numeric array.
Array types
A NumPy array has a data type, often called its dtype. This type determines how the values are represented. An array of integers and an array of floating-point values will generally have different types.
An array is usually intended for numerical or similarly uniform data. It is possible to store strings or general objects in some NumPy arrays, but doing so often loses the performance advantages that make numeric arrays useful.
Slicing multidimensional arrays
A multidimensional array can be indexed by providing a selector for each dimension. In a two-dimensional array, the first selector addresses rows and the second addresses columns. Slices can be used in either dimension to select ranges.
This makes it possible to select a particular cell, an entire row or column, or a rectangular region. Assigning a compatible value or array to a selection updates that part of the array. NumPy can also broadcast a scalar across a selected region, applying the scalar value to each element.
Vectorized operations and broadcasting
A vectorized operation expresses an operation on entire arrays rather than writing a Python loop for each element. For example, adding a scalar to an array applies that addition to every element and produces an array of results.
Operations between arrays work element by element when their shapes are compatible. NumPy’s broadcasting rules also allow certain differently shaped arrays to work together by expanding dimensions conceptually. This avoids writing manual loops and is a major source of both convenience and speed.
Most ordinary array operations return a new result rather than changing the original array. In-place forms are available when modifying an existing array is intended.
Boolean arrays and filtering
Comparisons on arrays are vectorized too. A comparison such as “greater than a threshold” produces a Boolean array: each element is True or False according to whether it meets the condition.
That Boolean array can be used to select only matching elements. For example, an analyst can select all values greater than a chosen threshold without manually listing which positions qualify. This is a foundation for filtering data in both NumPy and pandas.
Conditions can be combined using Boolean logic, such as AND, OR, and NOT. In NumPy, the element-wise operators are commonly written as & for AND and | for OR, with each comparison enclosed in parentheses. This is distinct from Python’s scalar Boolean operators, which are not substitutes for element-wise array logic.
Statistics and linear algebra
NumPy provides common numerical operations, including sums, means, standard deviations, and variances. These can be applied to an entire array or along a particular axis.
For a two-dimensional array:
Reducing along axis 0 combines values down the rows, producing one result per column.
Reducing along axis 1 combines values across the columns, producing one result per row.
NumPy also supports linear-algebra operations such as matrix multiplication, transposition, and related calculations. Its numerical routines are designed to work efficiently with array data.
Performance and appropriate use
For large numeric workloads, NumPy operations can be much faster and more memory-efficient than equivalent Python loops over lists. The difference becomes more noticeable as the amount of data and computation grows.
It is not necessary to understand every low-level detail before using NumPy. Analysts can begin with its ordinary array operations and learn about type widths, memory, or performance bottlenecks when those issues become relevant.
pandas: Tabular Data Analysis
pandas is the main Python library for many everyday data-analysis tasks. It supports reading data, inspecting it, cleaning it, transforming it, combining it, summarizing it, and producing basic plots. Its core structures are the Series and the DataFrame.
Series
A Series is a one-dimensional sequence of values with an associated index. It is backed by an array and usually has a consistent data type.
A Series resembles both a list and a dictionary:
Like a list, it is ordered and supports selection by position.
Like a dictionary, its values can be selected using labels in its index.
Unlike an ordinary dictionary, it retains an ordering of its elements.
A Series can use the default integer index or a custom index with meaningful labels. For example, a Series of country populations can use country names as labels. This allows a value to be selected by country name rather than by remembering its position.
Label-based and position-based selection
pandas distinguishes label-based selection from position-based selection:
.locselects using index labels..ilocselects using integer positions.
This distinction is important when the index is not a simple sequence of integers. A Series can also be selected using a list of labels, a slice, or a Boolean condition.
Slice behavior differs by selector. With label-based .loc slicing, the ending label is generally included. With position-based .iloc slicing, the ending position is excluded, following ordinary Python slicing conventions.
Series calculations and filtering
Numerical operations on a Series are vectorized. Adding, multiplying, or comparing values can operate across the whole Series without a manually written loop. Statistical operations such as mean, median, and standard deviation are also available.
A comparison can create a Boolean Series, which can then filter the original Series. Multiple conditions can be combined to select values that meet more than one requirement. Series values can be changed through direct assignment or assignment to a filtered selection.
DataFrames
A DataFrame is a two-dimensional, table-like structure with labeled rows and columns. It resembles a spreadsheet, but its columns have data types and it supports programmatic operations on large datasets.
A DataFrame can be understood as a collection of Series, typically one per column. The row index and the column labels are both meaningful parts of its structure.
Useful inspection tools include:
Shape, which reports the number of rows and columns.
Info, which summarizes columns, types, and non-missing-value counts.
Describe, which reports summary statistics for numeric columns.
Head and tail, which show a small number of rows from the beginning or end.
These summaries help an analyst understand a dataset without examining all its rows.
Selecting rows and columns
Common DataFrame selection patterns include:
Selecting a column by its name returns a Series.
Using
.locselects rows by index label and can also select columns.Using
.ilocselects rows and columns by integer position.Boolean conditions select rows that satisfy a criterion.
The first dimension in a two-dimensional selection refers to rows; the second refers to columns. Being explicit about label-based versus position-based selection helps prevent mistakes.
Alignment by labels
One of pandas’ important behaviors is alignment. When Series or DataFrames are combined, pandas uses their labels to match corresponding rows or columns rather than relying only on physical position.
For example, a Series of adjustment values can be applied to matching DataFrame columns by name. Missing labels may lead to missing values in the result. This behavior is useful when combining related data, but it also means that the index and column labels should be checked when results look unexpected.
Creating, changing, and dropping data
New columns can be created from existing columns using arithmetic or other transformations. A calculation such as revenue divided by population can produce a new Series, which can then be assigned as a DataFrame column.
Rows or columns can be dropped by label, and data can be renamed. Many pandas transformations return a new object unless the result is assigned back or an in-place option is used. Analysts should check whether an operation changes the existing object or returns a transformed copy, and should retain the result when needed.
Basic visualization
pandas can create common plots directly from Series or DataFrames. Its plotting methods use Matplotlib underneath, which makes quick charts convenient while still allowing more detailed customization through Matplotlib.
Cleaning Data
Data cleaning ranges from straightforward format repair to difficult judgments that depend on understanding the subject matter.
Missing values
A missing value may indicate that a field was not recorded, was unavailable, or was lost during processing. pandas provides functions such as isna and isnull to identify missing values; these names are commonly interchangeable. The corresponding notna and notnull functions identify present values.
These checks can be applied to a single value, a Series, or a DataFrame. Counting Boolean results can reveal how many values are missing or present in a column. DataFrame information summaries also provide non-missing counts.
Missing values can be handled in several ways:
Drop rows or columns that contain missing values.
Fill missing values with a chosen constant.
Fill values using a statistic, such as a mean, when that choice is appropriate.
Forward-fill from an earlier value or backward-fill from a later one when the order has meaning.
Dropping missing data requires care. By default, a DataFrame drop operation may remove a row if any selected value in that row is missing. Options can change whether rows or columns are considered and how many valid values are required for an entry to be kept. Filling with a mean or another replacement also requires a reason: a replacement can distort the analysis if it does not represent the missing data appropriately.
Invalid values
An invalid value violates the expected format or allowed categories. Examples include text in a field that should contain numbers, or an unrecognized code in a category column.
The expected rules should be established first. A category column might be expected to contain only specified labels, while a numeric column should contain numbers. Methods such as unique-value checks and value counts can help identify unexpected entries. Replacements can then correct known, well-understood errors.
Values that are valid in form but implausible in context
Some errors are harder to find because they are technically valid values. For example, a customer age of 170 is a valid integer but is implausible for a human customer. A mistaken extra zero might explain it, but that explanation needs evidence.
This stage requires domain knowledge. A value that is unusual in one field may be normal in another. For example, a measurement that seems extremely high to someone unfamiliar with a scientific field may be ordinary for that field. Analysts should consult subject-matter experts or data owners when the meaning of a value is uncertain.
Duplicates
Before removing duplicates, the analyst must decide what counts as a duplicate. Two records may match on one field but represent different entities when other fields are considered.
Duplicate-detection operations can identify repeated rows or values. Their behavior often depends on whether the first occurrence, the last occurrence, or every occurrence is treated as a duplicate. A subset of columns can be specified when only certain fields define identity.
For example, two player records with the same name might represent the same person if all relevant fields match, or different records if their positions or seasons differ. The chosen duplicate rule should reflect the purpose of the dataset.
String handling
Text fields often require normalization. pandas provides string-specific methods through the string accessor, including operations to:
Split strings on a chosen separator.
Check whether a string contains a pattern.
Strip unwanted characters or whitespace.
Replace text, including with regular-expression patterns.
Expand split results into multiple columns.
These operations can help standardize inconsistent text before analysis. Data types matter: string methods apply to text-like columns, while date/time and categorical columns have their own specialized operations.
Statistical inspection and outliers
Plots and summary statistics help reveal unusual observations. Box plots show medians, quartiles, and potential outliers; histograms and density plots show the shape of a distribution.
An outlier is not automatically an error. Its interpretation depends on the data and the question. A value may be plausible in a general population but unusual in a narrower group, such as a dataset limited to high-school students. The analyst should investigate unusual values before removing them.
Reading and Writing Data
pandas provides functions for common file formats and databases. Reading data into a DataFrame allows the same analysis tools to be applied across different sources.
CSV and text files
A CSV is a text-based representation of tabular data. Although CSV stands for comma-separated values, fields may use other separators. Files may also differ in whether they include a header, how they represent missing values, how they quote text, and how dates are formatted.
pandas’ CSV-reading function supports options for these details, including:
Whether a header is present.
Column names and data types.
The field separator.
Values to interpret as missing.
Rows to skip.
Columns to use as an index.
Columns to parse as dates.
The analyst should inspect the loaded DataFrame to confirm that the columns, types, and missing values were interpreted correctly. A date column that has been read as ordinary text may need to be converted to a date/time type.
A CSV can also be written from a DataFrame. Writing options can determine whether to include the index or header and which separator to use.
Reading and writing files with Python
At a lower level, Python can open a file and read its contents line by line or in blocks. Specialized modules can parse formats such as CSV. These lower-level approaches offer control, but the analyst must handle details such as separators and formatting. pandas provides a more convenient interface for many routine data-analysis tasks.
SQL databases
To work with a database, the appropriate database connector must be installed. The exact connector depends on the database system, but the general workflow is similar:
Create a connection.
Write or select a SQL query.
Execute it.
Load the result into a DataFrame.
pandas can execute a SQL query and return its results in tabular form. SQLAlchemy can be used for database connections and for reading tables through a higher-level interface. The relevant support and setup depend on the database and environment.
pandas can also write DataFrame contents to a database table. The analyst must choose what to do if the table already exists—for example, fail, replace it, or append rows. Replacing a table can destroy existing data, so that behavior should be selected deliberately.
HTML tables
pandas can parse tables from HTML pages. This can be useful for quick exploration when a page contains a well-structured table, such as a public statistics table.
The parser may find multiple tables, so each result should be inspected to identify the relevant one. HTML is designed primarily for presentation, not necessarily for machine analysis. Complex or irregular page structure, repeated headers, merged cells, or formatting intended for human readers can require substantial cleanup. If a service provides a data API, that may be more reliable than parsing the visible page.
Excel files
Excel workbooks are not plain text and commonly require an appropriate supporting library. A workbook can contain multiple sheets; each sheet is generally read into a separate DataFrame.
The analyst can select a specific sheet, inspect the available sheet names, and configure headers or indexes. Writing to Excel can produce one or more sheets, depending on the chosen workflow and installed libraries. Compatibility may depend on the spreadsheet format and the software environment.
Visualizing Data with Matplotlib and Related Tools
Visualization helps analysts understand distributions, comparisons, and relationships. Matplotlib is a foundational plotting library in the Python data ecosystem. pandas uses Matplotlib for many of its plotting methods, while Seaborn offers a higher-level interface for statistical visualizations. Bokeh can be used when interactive plots are useful.
Common chart types
Box plots summarize a distribution through its median, quartiles, and potential outliers. They are useful for comparing distributions across groups.
Histograms divide numeric values into bins and show how many observations fall into each range.
Density plots provide a smoothed representation of a distribution.
Bar charts compare category counts or values.
Scatter plots display paired numeric observations and can reveal a relationship, clustering, or outliers.
Correlation heatmaps use color to summarize correlation values. The color scheme is a visualization choice; the values, not the colors alone, determine the interpretation.
Bubble charts can encode additional variables using position, color, or marker size.
Charts should be chosen to match the question. A histogram shows a distribution, while a scatter plot is more appropriate for examining the relationship between two numeric variables.
Matplotlib’s two interfaces
Matplotlib provides both a state-based, often called pyplot, interface and an object-oriented interface.
The state-based approach issues plotting commands through a shared plotting state. It can be concise for simple figures, but in complex notebooks it may be harder to determine which plot each command affects.
The object-oriented approach creates a figure and explicit axes. Plotting commands are then directed to a particular axes object.
Explicit axes can make multi-plot figures easier to read and maintain because each chart is clearly associated with its own plotting area.
Static and interactive charts
A static chart is useful for reports and exports where the appearance should remain fixed. Interactive charts can support exploration by allowing zooming, panning, or inspection of particular regions. Interactivity is especially useful when an analyst wants to investigate a local feature of a plot; a static image may be more suitable for a final document or report.
Python Essentials for Analysis
Python is a high-level, general-purpose programming language used for data analysis and many other kinds of software. The language is dynamically typed: a variable can be assigned values without a separate type declaration. Python is also strongly typed, meaning that operations must make sense for the types involved.
Python 3 is the current major version to use. Python 2 is obsolete and should not be used for new work.
Indentation and code blocks
Python uses indentation to define blocks of code, such as the body of a function, conditional, or loop. Consistent indentation is therefore part of the program’s structure, not merely a visual style.
Comments begin with the hash symbol. Variables can be created by assigning a value to a name, and functions are defined using a function definition with parameters and, where needed, a return value.
Common data types
Important built-in types include:
Integers for whole-number values.
Floating-point numbers for approximate decimal values.
Strings for text.
Booleans for true-or-false values.
None to represent the absence of a value.
Conversion functions can change a value from one compatible type to another. Such conversions can fail if the value does not have a valid representation in the requested type.
Collections
Python’s common collection types serve different purposes:
Lists are ordered, mutable sequences. They can be indexed and changed after creation.
Tuples are ordered sequences that cannot normally be changed after creation.
Dictionaries map keys to values, making it possible to look up a value by a meaningful key.
Sets contain unique values and are useful for membership checks and set operations.
Python collections can contain different types, but mixing unrelated types can make data harder to reason about. Uniform and clearly structured collections are usually easier to use.
Lists, tuples, and strings use zero-based indexing. Negative positions count from the end of a sequence. Dictionaries are best understood as key–value mappings rather than as sequences to index by position.
Loops and control flow
Conditional statements select which block of code to run. Python supports if, elif, and else.
A for loop commonly iterates over the values of a collection. A while loop repeats as long as a condition remains true, but it can continue indefinitely if its condition is not updated correctly. A for loop is generally suitable when iterating through a known collection.
Functions, modules, and exceptions
Functions package reusable behavior. They can receive parameters and return results. A function with no explicit return value returns None.
Modules and packages group reusable code. Python includes a standard library, and external libraries can be installed for tasks such as numerical computing, visualization, and machine learning.
Exceptions signal that an operation could not be completed—for example, because of an invalid type or an unavailable file. Exception handling allows a program to respond to expected errors rather than terminating without explanation.
These fundamentals are sufficient to begin exploring data with Python. More advanced work builds on the same ideas: structured data, reusable transformations, clear control flow, and careful handling of errors.

Ask anything
We've read this whole study set, so questions about it get the best answers.