Python for Data Science Beginners: Complete Step-by-Step Tutorial with Examples
You have a small table containing the number of hours students studied and their practice-test scores. Instead of finding every average by hand, imagine typing a few lines of code, checking the results and creating a chart. That is a realistic first step into data science with Python—and you can follow it with a free coding environment.
This Python for data science beginners tutorial teaches you through working programs, not just definitions. You will write Python from scratch, use NumPy for numeric calculations, explore Pandas tables, read a CSV file, clean messy records, draw charts and complete one mini-investigation. The examples work for students worldwide and need no prior coding experience.
Our recurring dataset contains five fictional study-hour and test-score pairs. It is invented for practice, not collected from actual learners. You will keep those five observations consistent throughout the examples, so a chart, a DataFrame and the answers can be checked against one another.
By the end: run a Python cell; understand variables, lists, conditions, loops and functions; use NumPy and Pandas; inspect a CSV; handle a duplicate and a missing value; create a scatter plot; and describe a pattern without claiming it proves causation.
In this tutorial
- What Python does in data science
- Why learn Python?
- Set up Python: Colab or local
- Six beginner Python fundamentals
- First analysis: Mean study hours
- NumPy arrays and statistics
- Pandas DataFrames
- Read a reproducible CSV file
- Clean missing and duplicate data
- Choose and make Python charts
- Complete mini-project
- Troubleshoot common errors
- Free practice resources
- Four-week practice plan
- Ten coding exercises and solutions
- Frequently asked questions
What is Python for data science?
Python is a free, general-purpose programming language. Ordinary programming might send messages or create applications. Data science with Python uses programs to organize observations, identify errors, calculate statistics, make figures and support decisions. More advanced work may fit predictive models, but a beginner should first learn how to trust and interpret a simple dataset.
For a real school-weather question, Python could combine hundreds of daily measurements into a monthly summary. The computer will apply a calculation consistently, yet people must still check units, missing days and where the readings came from. Correct code cannot rescue a poorly designed investigation.
Why is Python popular for data science?
Python’s readable syntax, open-source availability and broad community make it accessible. NumPy handles numerical arrays; Pandas handles tables; Matplotlib makes charts; and other libraries support statistical modeling. Jupyter notebooks combine code, explanations and outputs, which makes them helpful for science projects and classroom demonstrations.
Reuse is another advantage: once a calculation works, you can run it on new records without retyping formulas. But Python still requires debugging, appropriate package versions and critical interpretation. Beginners must learn what each line does rather than copying mysterious notebooks or treating a computer output as unquestionable.
How to set up Python for data science
Option 1: Google Colab — start in a browser
Open Google Colab with an eligible Google account, create a new notebook, click a code cell, type print('Hello, data!') and press its Run icon or Shift+Enter. The notebook displays Hello, data! underneath. Colab runs code on a hosted environment, so no initial package installation is usually necessary for these common libraries.
Colab is free of charge for some computing use, but its resources, availability, session duration and account conditions vary. A stable connection helps; use a school-approved account and check minimum-age requirements. Never paste passwords or private student records into a shared notebook.
Option 2: Install Python on your computer
Download Python from Python.org and follow the official instructions for your operating system. Use the included IDLE editor, a suitable text editor or a Jupyter notebook. In a terminal, check python --version or python3 --version, depending on your system. Run a file such as hello.py using the corresponding Python command.
The first programs below need only Python itself. NumPy, Pandas and Matplotlib require their packages when not already available; a typical local setup is python -m pip install numpy pandas matplotlib. Depending on your operating system, use python3 -m pip instead. If installation is restricted on a school device, use a permitted browser notebook.

Six essential Python fundamentals for beginners
1. Variables and data types
A variable gives a value a name. Python supports integers, decimal floats, text strings and Boolean true/false values. Names are case-sensitive, so hours and Hours differ. Strings need quotation marks; numbers usually do not.
hours = 4
score = 70.0
subject = "Mathematics"
completed = True
print(subject, hours, completed)
Expected output: Mathematics 4 True. The example stores different kinds of information. Try changing hours to 5, then print it again.
2. Lists and indexing
A list stores several values in order. Python indexes start at zero: the first item is at position 0, not 1. Use a list when you want to collect multiple readings before calculating a summary.
study_hours = [2, 3, 4, 5, 6]
print(study_hours[0])
print(len(study_hours))
Output: 2 and 5 on separate lines. Try printing the final element with study_hours[-1]; the answer is 6.
3. Arithmetic operators
Use + for addition, - for subtraction, * for multiplication and / for division. ** raises a value to a power, while % finds a remainder. Parentheses help make the order clear.
total = 2 + 3 + 4 + 5 + 6
mean = total / 5
print(total, mean)
Output: 20 4.0. The number 4.0 is the arithmetic mean of the five weekly-hour values, not a prediction.
4. Conditions: if, elif and else
A conditional program selects an action based on a comparison. Indent the statements underneath each condition. Test the most restrictive case first if later cases overlap.
score = 70
if score >= 80:
print("High")
elif score >= 60:
print("Middle")
else:
print("Lower")
Output: Middle. These categories are invented for practice and are not official school grade boundaries. Try score = 85; it should print High.
5. Loops repeat a calculation
A for loop processes each item in a collection. In the following example it prints each study-hour value doubled; the loop variable takes one value at a time.
for hour in [2, 3, 4, 5, 6]:
print(hour * 2)
Output: 4, 6, 8, 10 and 12 on separate lines. Add a sixth number to the list and observe that the loop processes it too.
6. Functions make code reusable
A function groups steps under a name and can return a result. Our function checks for an empty list before dividing, avoiding a common error that a rushed script would miss.
def average(values):
if not values:
return None
return sum(values) / len(values)
print(average([2, 3, 4, 5, 6]))
Output: 4.0. The function can analyze another nonempty list without rewriting the mean formula. Test an empty list; it returns None rather than crashing.
Your first Python data analysis: Mean study hours
Now combine the ideas. This is a tiny fictional dataset: five weekly study-hour values, all in the same unit. A Python list holds them and built-in functions calculate the mean, smallest and largest values. No library imports are required.
study_hours = [2, 3, 4, 5, 6]
average_hours = sum(study_hours) / len(study_hours)
print("Average study hours:", average_hours)
print("Minimum:", min(study_hours))
print("Maximum:", max(study_hours))
Expected output: Average study hours: 4.0, Minimum: 2 and Maximum: 6. The mean is the sum 20 divided by five observations; the minimum and maximum describe the smallest and largest values, not how typical any real student is.
Try it yourself: Replace the last number 6 with 8 and calculate the new mean before running the program. Answer: (2 + 3 + 4 + 5 + 8) ÷ 5 = 4.4. Always state whether your values are real, sourced or fictional.
NumPy for beginners: Arrays and fast statistics
NumPy provides an ndarray, a numerical array designed for efficient operations. A Python list can hold mixed kinds of objects, but a NumPy array normally contains values of a consistent type. This makes calculations across many elements straightforward.
import numpy as np
scores = np.array([55, 62, 70, 81, 92])
print("Average:", np.mean(scores))
print("Highest:", np.max(scores))
print("Lowest:", np.min(scores))
print("Add five:", scores + 5)
Expected results: Mean 72.0, highest 92, lowest 55; adding five produces [60 67 75 86 97]. That last operation adjusts each array element. With a plain Python list, adding a number directly would raise a type error rather than perform elementwise arithmetic.
NumPy is useful for repeated measurements, matrices, simulations and numerical statistics. Yet a five-element school exercise does not need it for speed; we introduce it here to show the same principles used for larger calculations. Try np.median(scores); the median is 70.0.
Pandas tutorial: Build and inspect a DataFrame
Pandas helps work with labeled rows and columns. A Series behaves like one labeled column; a DataFrame is a two-dimensional table. We will use the same five fictional cases and five scores from the NumPy example, now linked to hours and anonymous student labels.
import pandas as pd
df = pd.DataFrame({
"Student": ["A", "B", "C", "D", "E"],
"StudyHours": [2, 3, 4, 5, 6],
"TestScore": [55, 62, 70, 81, 92]
})
print(df)
print("Mean:", df["TestScore"].mean())
print("Rows, columns:", df.shape)
| Student | Study hours | Fictional score |
|---|---|---|
| A | 2 | 55 |
| B | 3 | 62 |
| C | 4 | 70 |
| D | 5 | 81 |
| E | 6 | 92 |
Expected numerical output: Mean: 72.0 and Rows, columns: (5, 3). Pandas prints the table with row indices 0–4. Use df['TestScore'] to select one column, df.head() to preview the first five rows and df.describe() for summary statistics.
Averages cannot reveal everything. The scores have median 70 and range 37 (92 − 55), so the dataset also has variation. Describe the number of observations and units whenever sharing a statistic.

How to read CSV data with Pandas
A CSV (comma-separated values) file stores rows of text with commas between columns. Real school research might export such a file from a spreadsheet. Below, we create a deliberately imperfect sample ourselves: five intended observations, one duplicate and one record with a missing score. You do not need to download a file or expose anyone’s grades.
from pathlib import Path
csv_text = """Student,StudyHours,TestScore
A,2,55
B,3,62
C,4,70
D,5,81
E,6,92
E,6,92
F,7,
"""
Path("study_scores_raw.csv").write_text(
csv_text, encoding="utf-8"
)
print("Created study_scores_raw.csv")
Output: Created study_scores_raw.csv. This file is written in the current working directory; in a hosted notebook it may disappear when the runtime resets. The final F row has a blank score, and E appears twice by design. Those defects are useful practice for your cleaning steps.
import pandas as pd
raw = pd.read_csv("study_scores_raw.csv")
print(raw.head())
print("Shape:", raw.shape)
print("Columns:", raw.columns.tolist())
print("Missing:", raw.isna().sum().to_dict())
Expected checks: the raw file has 7 rows and 3 columns; the columns are Student, StudyHours and TestScore; only TestScore has one missing value. If Python reports FileNotFoundError, run the creation cell first or provide the correct path.
Data cleaning with Pandas: Missing and duplicate values
Real datasets may contain repeated records, blanks, inconsistent labels, wrong units, unexpected types or implausible values. Cleaning means investigating and documenting such issues. It does not mean silently removing every inconvenient observation.
Start by inspecting raw.isna().sum() for missing values and raw.duplicated().sum() for exact repeated rows. Our fictional data deliberately include one duplicate and one missing score. Missing is not automatically zero: a student who did not submit a score is not necessarily someone who scored zero.
print("Duplicates:", raw.duplicated().sum())
print("Missing scores:", raw["TestScore"].isna().sum())
clean = raw.drop_duplicates().copy()
clean["StudyHours"] = pd.to_numeric(
clean["StudyHours"], errors="coerce"
)
clean["TestScore"] = pd.to_numeric(
clean["TestScore"], errors="coerce"
)
clean = clean.dropna(
subset=["StudyHours", "TestScore"]
)
print("Clean shape:", clean.shape)
print("Clean mean:", clean["TestScore"].mean())
Verified output: Duplicates: 1, Missing scores: 1, Clean shape: (5, 3) and Clean mean: 72.0. We removed the repeated identical E row and excluded F because this exercise needs complete score-and-hours pairs. That is one defensible choice for this particular descriptive exercise, not a universal rule for research.
Investigate the reason for missingness before deciding whether to exclude, impute or collect a value. For instance, fillna(0) substitutes zero but would misrepresent an unknown score here. Keep the original file unchanged so you can explain each transformation and reproduce your findings.

Python data visualization: Choose the right chart
Matplotlib creates charts directly in Python; Seaborn offers higher-level statistical graphics built on Matplotlib. Use a bar chart for categories, a line graph for readings in time order, a histogram for a numerical distribution and a scatter plot for two numerical variables.
| Chart type | Good beginner use | Watch out for |
|---|---|---|
| Bar | Category totals | Unequal units or truncated axis |
| Line | Measurements ordered by time | Missing dates or changing intervals |
| Histogram | Distribution of one numeric variable | Bin widths and sample size |
| Scatter | Relationship between numeric variables | Causation and misleading scales |
Here the two numerical variables are weekly study hours and practice scores, so a scatter plot is appropriate. The source is still our same five-row cleaned dataset. You can run this cell after the cleaning code:
import matplotlib.pyplot as plt
plt.scatter(clean["StudyHours"], clean["TestScore"])
plt.xlabel("Study hours per week")
plt.ylabel("Fictional practice score (out of 100)")
plt.title("Study hours and scores — fictional data")
plt.xlim(1.5, 6.5)
plt.ylim(45, 100)
plt.grid(alpha=0.3)
plt.show()
The graph contains five points: (2,55), (3,62), (4,70), (5,81) and (6,92). Labels communicate the variables and units. The upward pattern is an association intentionally built into invented data; it cannot show that studying longer caused any real improvement.

Complete beginner project: Analysing study hours and test scores
A full data science project brings the earlier pieces together. Research question: what descriptive relationship appears between the two fictional variables? We need one labeled dataset, a record of quality checks, basic statistics, a chart, a cautious conclusion and documentation that another learner could reproduce.
The following self-contained program creates the imperfect CSV file, reads it, removes its single duplicate, excludes its one missing score, computes statistics and saves a figure. It requires Pandas and Matplotlib but no NumPy import in this particular cell. Run the entire block in one Python environment.
from pathlib import Path
import pandas as pd
import matplotlib.pyplot as plt
csv_data = """Student,StudyHours,TestScore
A,2,55
B,3,62
C,4,70
D,5,81
E,6,92
E,6,92
F,7,
"""
Path("study_scores_raw.csv").write_text(
csv_data, encoding="utf-8"
)
raw = pd.read_csv("study_scores_raw.csv")
print("Raw records:", len(raw))
print("Duplicates:", int(raw.duplicated().sum()))
print("Missing scores:", int(raw["TestScore"].isna().sum()))
clean = raw.drop_duplicates().copy()
for col in ["StudyHours", "TestScore"]:
clean[col] = pd.to_numeric(clean[col], errors="coerce")
clean = clean.dropna(subset=["StudyHours", "TestScore"])
print("Clean records:", len(clean))
print("Average hours:", clean["StudyHours"].mean())
print("Average score:", clean["TestScore"].mean())
print("Median score:", clean["TestScore"].median())
print("Score range:", clean["TestScore"].max()
- clean["TestScore"].min())
plt.scatter(clean["StudyHours"], clean["TestScore"])
plt.xlabel("Study hours per week")
plt.ylabel("Fictional practice score (out of 100)")
plt.title("Study hours and scores — fictional data")
plt.xlim(1.5, 6.5)
plt.ylim(45, 100)
plt.grid(alpha=0.3)
plt.savefig("study_hours_scores.png", dpi=160)
plt.show()
Verified outputs: Raw records 7; Duplicates 1; Missing scores 1; Clean records 5; Average hours 4.0; Average score 72.0; Median score 70.0; Score range 37.0. Your program also creates study_hours_scores.png. File locations depend on where Python is running.
Write your finding: in these invented observations, scores increase as the recorded hours increase. State the limitation: the dataset is fictional, contains five observations, lacks a scientifically selected sample and cannot estimate a real causal effect. A genuine project would need permission, documented measurements, careful sampling and attention to factors such as prior knowledge and teaching conditions.
For a first presentation, show the data table, explain the cleaning decisions and use the scatter plot to discuss the observed pattern. Separate what the chart shows from what further research would need to determine. In a portfolio, retain the notebook, the created CSV and a short README describing every step.

Common Python errors and how to debug them
- SyntaxError: a missing quotation mark, colon or bracket; inspect the exact line and punctuation.
- IndentationError: inconsistent indentation after a function, loop or conditional; use consistent spaces.
- NameError: an undefined or misspelled variable; rerun the cell that defines it.
- ModuleNotFoundError: the intended library is absent from that environment; install the right package if permitted.
- FileNotFoundError: a filename or directory is wrong; create the CSV first and check the working directory.
- TypeError: a string is used as a number or a Python list is treated like an array; inspect types and conversions.
- ValueError: a conversion or operation receives unsuitable values; inspect the data without inventing replacements.
- Wrong results: even valid syntax can produce incorrect calculations; test against a small hand-checked example.
Read the last part of an error traceback, identify the first relevant line in your own program and change one thing at a time. Save working versions so you can return to them. An AI explanation can help you understand an error, but you must check the suggested code by running it.
Best free resources for learning Python and data science
Use the official Python tutorial and getting-started resources for language references. The official tutorial assumes some general programming familiarity, so first-time coders may prefer guided lessons.
Khan Academy Python Fundamentals and freeCodeCamp offer structured beginner practice. Kaggle Learn Python and Kaggle Pandas provide notebook-based exercises, subject to account requirements; Colab is a notebook environment, not a course.
The Pandas tutorials, NumPy beginner guide and Matplotlib documentation are direct references when you are ready to work beyond the first examples. Course fees, free access, device compatibility and permitted minimum ages may differ across regions.

University of Michigan · Coursera · Optional course
Python for Everybody Specialization
Optional structured practice in Python programming, data structures and real coding concepts, suitable after the first examples.
Official course URL, not an approved affiliate-tracking link. Paid study is not required for this tutorial.

Udemy · Optional course
The Complete Python Bootcamp From Zero to Hero
Optional video-led Python fundamentals, functions, coding exercises and projects. Verify the current price before enrolling.
Official course URL, not an approved affiliate-tracking link. Paid study is not required for this tutorial.
Four-week Python for data science practice plan
| Week | Learning priority | Practical evidence |
|---|---|---|
| 1 | Python basics: values, lists, conditions, loops and functions | Three working scripts with explanations |
| 2 | NumPy arrays; Pandas tables and summaries | Reproduce the five-row DataFrame |
| 3 | CSV files, missing values, duplicates and Matplotlib charts | Checked cleaning log and scatter plot |
| 4 | Complete an independent beginner project | Notebook, figure and limitations report |
A useful routine is a short reading session followed immediately by writing and modifying code. Keep notes on errors and how you solved them, not only screenshots of successful output. If you have limited computer time, trace the program on paper and execute it during your next available session.
Ten practice exercises with solutions
Try each task before revealing the suggested solution. These questions progress from basic arithmetic toward cleaning and explaining small datasets. Every dataset is fictional unless the exercise asks you to choose a properly documented public source.
1. Calculate an average
Try: Compute the mean of [4, 6, 8] with sum() and len().
Show suggested solution
sum([4,6,8])/3 gives 6.0.
2. Find extremes
Try: Find the minimum and maximum of [55, 62, 70, 81, 92].
Show suggested solution
min(scores) is 55; max(scores) is 92.
3. Use a loop
Try: Print every value in [2,3,4] doubled.
Show suggested solution
for n in [2,3,4]: print(n*2) using proper indentation prints 4, 6, 8.
4. Write a function
Try: Create a function that returns the range of a nonempty numeric list.
Show suggested solution
def spread(values): return max(values)-min(values) with an indented return.
5. Create an array
Try: Turn [1,2,3] into a NumPy array, then add 2 to every element.
Show suggested solution
np.array([1,2,3])+2 gives [3 4 5].
6. Make a table
Try: Create a Pandas DataFrame with columns Hours [2,3] and Score [55,62].
Show suggested solution
pd.DataFrame({'Hours':[2,3],'Score':[55,62]}) creates two rows.
7. Select one column
Try: Extract scores from the DataFrame above and find their mean.
Show suggested solution
frame['Score'].mean() equals 58.5.
8. Handle missing data
Try: You find a blank practice score. Should it become zero automatically?
Show suggested solution
No. Check why it is missing; choose a justified approach and document it.
9. Choose a graph
Try: Visualize the relationship between study hours and scores.
Show suggested solution
Use a scatter plot, with units and a title. The points do not prove causality.
10. Interpret a pattern
Try: Scores rise in our invented five-row dataset. What may you conclude?
Show suggested solution
A positive descriptive association exists in these fictional rows; no claim about real-world cause is justified.
Frequently asked questions
Can I learn Python for data science without coding experience?
Yes. Begin with variables, lists and basic calculations, then add NumPy, Pandas and charts after you can explain simple programs.
Is Python difficult for a complete beginner?
It takes practice, especially debugging and handling files, but short working examples are an approachable starting point.
Is Python software free?
The Python language and common libraries such as NumPy, Pandas and Matplotlib are free and open source; service charges or internet costs may differ.
How long does learning Python for data analysis take?
There is no fixed time. The four-week plan is a practice outline, not a guarantee that every reader will master it.
Do I need advanced mathematics?
No for your first projects. Arithmetic, averages and graph reading suffice initially; advanced research requires more statistics.
What is the difference between NumPy and Pandas?
NumPy centers on numerical arrays and efficient operations; Pandas adds labeled tabular data with rows, columns and cleaning tools.
Can I use Google Colab on a phone?
Some notebooks can open on mobile browsers, but long code and visualizations are easier on a computer. Account and connection requirements apply.
Which Python data science library should I learn first?
Learn Python fundamentals first, then NumPy for arrays and Pandas for tables. Use Matplotlib when you need charts.
Should beginners study machine learning immediately?
No. Understand data sources, cleaning, basic statistics and testing before moving to predictive models.
What project should I build after this tutorial?
Analyze a small fictional budget, public weather table or licensed sports dataset, then document your question, methods, chart and limitations.
Conclusion: Build skill one reproducible example at a time
You have progressed from your first Python commands to lists, conditions, loops, reusable functions, numerical arrays, labeled tables, CSV files, data cleaning and a real charting workflow. The same five fictional observations let you check whether each stage produces sensible results. You also saw why a missing value is not necessarily zero, and why an upward scatter plot is not proof of causation.
The strongest next step is repetition with understanding. Type each example, predict its output, run it, investigate any error and explain what the results actually measure. Then choose one new, safely sourced or clearly fictional dataset and prepare a short independent report with code and transparent limitations.
To continue, visit Data Science Projects for High School Students, How to Build a Data Science Portfolio, or Python Certifications for Students once the foundations are strong.
Related reading: Continue learning with Notes for SHS
- Introduction to Data Science — the concepts behind the methods
- How to Get Started with Data Science in High School — learning roadmap
- Learning Python for Data Science in High School — course and tool guidance
- Best Data Science Tools and Techniques — software comparison
- The Importance of Math in Data Science — statistics foundations
- How to Master Data Cleaning — deeper cleaning skills
- Data Science Career Paths After High School — future options
References and disclosure: Official Python, NumPy, Pandas, Matplotlib and Google Colab documentation reviewed November 2026. Course recommendations use official untracked URLs, not verified affiliate links. Neither enrollment nor a certificate is required to complete this tutorial.
1 response to “Python for Data Science Beginners: Complete Step-by-Step Tutorial with Examples”