Tuesday, July 7, 2026
HomeData SciencePython for Data Science: Complete Beginner's Guide (2026)

Python for Data Science: Complete Beginner’s Guide (2026)

Table of Content

Python is the language of data science. Not because it is the fastest language (it is not), or the most elegant (reasonable people disagree), but because it has the best ecosystem — the most libraries, the most tutorials, the most Stack Overflow answers, and the most practitioners who can help you when you are stuck. If you are starting your data science journey in 2026, Python is where you start.

This guide assumes you have never written a line of Python. It covers the fundamentals you need to move from complete beginner to being able to load, explore, and visualise a real dataset. Every concept includes a code example you can run immediately in Jupyter Notebook or Google Colab.

Setting Up Your Environment

The fastest way to get started is Google Colab — a free, browser-based Python environment with no installation required. Go to colab.research.google.com, sign in with a Google account, and you have a working Python environment with most data science libraries pre-installed. Use Colab while you are learning; it removes setup friction entirely.

When you are ready for a local environment, install Anaconda — a Python distribution that includes Python, Jupyter Notebook, and over 150 data science libraries in one installer. Download from anaconda.com, install, and launch Jupyter Notebook from the Anaconda Navigator. This is the setup used by most data scientists working locally.

Python Fundamentals: What You Actually Need

You do not need to master all of Python before working with data. Focus on these core building blocks:

# Variables and data types
name    = "Durgesh"           # string
age     = 28                  # integer
salary  = 75000.50            # float
is_active = True              # boolean

print(f"Name: {name}, Age: {age}, Salary: ₹{salary:,.2f}")

# String operations
course = "Data Science"
print(course.upper())         # DATA SCIENCE
print(course.lower())         # data science
print(len(course))            # 12
print(course.split(' '))      # ['Data', 'Science']
print(f"I am learning {course} in 2026")
# Lists — ordered, mutable collections
scores = [85, 92, 78, 95, 88]
print(scores[0])              # 85 — first element
print(scores[-1])             # 88 — last element
print(scores[1:4])            # [92, 78, 95] — slicing

scores.append(91)             # add to end
scores.sort()                 # sort in place
print(sum(scores) / len(scores))   # average

# Dictionaries — key-value pairs (like a lookup table)
student = {
    'name':   'Priya',
    'age':    24,
    'course': 'Data Science',
    'score':  92.5
}
print(student['name'])        # Priya
student['city'] = 'Mumbai'    # add new key
print(student.keys())         # all keys
print(student.values())       # all values
# Loops
for score in scores:
    if score >= 90:
        print(f"Excellent: {score}")
    else:
        print(f"Good: {score}")

# List comprehension — Pythonic shorthand
high_scores = [s for s in scores if s >= 90]
doubled     = [s * 2 for s in scores]

# Range
for i in range(5):      # 0, 1, 2, 3, 4
    print(i)
# Functions
def calculate_grade(score):
    if score >= 90:
        return 'A'
    elif score >= 80:
        return 'B'
    elif score >= 70:
        return 'C'
    else:
        return 'F'

# Apply to a list
grades = [calculate_grade(s) for s in scores]
print(dict(zip(scores, grades)))

NumPy: Fast Numerical Computing

import numpy as np

# Arrays — like lists but much faster for maths
arr = np.array([1, 2, 3, 4, 5])
print(arr * 2)              # [2 4 6 8 10] — vectorised (no loop needed)
print(arr ** 2)             # [1 4 9 16 25]
print(np.sqrt(arr))         # square root of each element

# Statistical operations
data = np.array([23, 45, 67, 12, 89, 34, 56, 78, 90, 11])
print(f"Mean:   {data.mean():.2f}")
print(f"Median: {np.median(data):.2f}")
print(f"Std:    {data.std():.2f}")
print(f"Min:    {data.min()}, Max: {data.max()}")

# 2D arrays (matrices)
matrix = np.array([[1, 2, 3],
                   [4, 5, 6],
                   [7, 8, 9]])
print(matrix.shape)         # (3, 3)
print(matrix[:, 1])         # second column: [2 5 8]
print(matrix[0, :])         # first row: [1 2 3]

# Random numbers (essential for ML)
np.random.seed(42)          # reproducibility
samples = np.random.normal(loc=0, scale=1, size=1000)
print(f"Random samples — mean: {samples.mean():.3f}, std: {samples.std():.3f}")

Pandas: Working with Real Data

import pandas as pd

# Create a DataFrame
data = {
    'city':    ['Mumbai', 'Delhi', 'Bengaluru', 'Chennai', 'Hyderabad'],
    'state':   ['Maharashtra', 'Delhi', 'Karnataka', 'Tamil Nadu', 'Telangana'],
    'population_m': [20.7, 19.8, 12.3, 10.9, 10.0],
    'avg_salary_lpa': [14.2, 12.8, 16.5, 11.3, 13.7]
}
df = pd.DataFrame(data)
print(df)
print(f"
Shape: {df.shape}")
print(f"
Stats:
{df.describe()}")

# Filter and select
high_salary = df[df['avg_salary_lpa'] > 13]
print(f"
Cities with avg salary > 13 LPA:
{high_salary[['city','avg_salary_lpa']]}")

# Add a new column
df['population_rank'] = df['population_m'].rank(ascending=False).astype(int)

# Sort
df_sorted = df.sort_values('avg_salary_lpa', ascending=False)
print(f"
Ranked by salary:
{df_sorted[['city','avg_salary_lpa']]}")

Your First Data Science Project

import matplotlib.pyplot as plt
import seaborn as sns

# Load a real dataset (Kaggle Titanic or any CSV)
url = 'https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv'
titanic = pd.read_csv(url)

print(f"Dataset: {titanic.shape[0]} passengers, {titanic.shape[1]} features")
print(f"
Survival rate: {titanic['Survived'].mean()*100:.1f}%")
print(f"
Missing values:
{titanic.isnull().sum()[titanic.isnull().sum() > 0]}")

# Survival by passenger class
survival_by_class = titanic.groupby('Pclass')['Survived'].mean() * 100
print(f"
Survival rate by class:
{survival_by_class.round(1)}")

# Visualise
fig, axes = plt.subplots(1, 2, figsize=(12, 5))

survival_by_class.plot(kind='bar', ax=axes[0], color='steelblue',
                       edgecolor='white', rot=0)
axes[0].set_title('Survival Rate by Passenger Class')
axes[0].set_ylabel('Survival Rate (%)')
axes[0].set_xlabel('Class')

titanic.groupby('Sex')['Survived'].mean().mul(100).plot(
    kind='bar', ax=axes[1], color=['coral', 'steelblue'], rot=0, edgecolor='white'
)
axes[1].set_title('Survival Rate by Gender')
axes[1].set_ylabel('Survival Rate (%)')

plt.suptitle('Titanic Survival Analysis', fontsize=14, fontweight='bold')
plt.tight_layout(); plt.show()

Once you are comfortable with these basics, your next steps are deepening Pandas knowledge through our Pandas cheat sheet, learning proper exploratory data analysis, and then moving into machine learning with scikit-learn.

Frequently Asked Questions

How long does it take to learn Python for data science from scratch?

With consistent practice of 1-2 hours daily, expect 6-8 weeks to become comfortable with the fundamentals covered in this guide — variables, loops, functions, NumPy basics, and Pandas for data loading and exploration. After that, building real projects accelerates learning dramatically. The concepts in this guide are straightforward; the challenge is not memorising syntax but developing the habit of thinking in data transformations. The fastest learners are those who pick a real dataset about something they find genuinely interesting and use it as the canvas for practising every new concept. Abstract exercises are useful; applying new knowledge to data you care about is transformative.

Should I learn Python 2 or Python 3?

Python 3, without question. Python 2 reached end-of-life in January 2020 and is no longer supported. All major data science libraries (Pandas, NumPy, scikit-learn, TensorFlow, PyTorch) require Python 3. All new tutorials, courses, and documentation use Python 3. If you encounter a tutorial that uses Python 2 syntax (most visibly: print "hello" without parentheses), it is outdated and you should find a more recent resource. Install Python 3.10 or later for the latest features and best library compatibility.

Jupyter Notebook or VS Code — which should I use for data science?

Use both for different purposes. Jupyter Notebook (and JupyterLab, its more capable successor) is the standard environment for data exploration and analysis — the cell-by-cell execution model lets you inspect results at each step, which is invaluable when exploring a new dataset. Most data science tutorials and examples use Jupyter format. VS Code is better for writing longer, more structured Python scripts — data pipelines, utility functions, and anything you want to run repeatedly with proper version control. A typical data science workflow: explore in Jupyter, clean up and productionise in VS Code. Start with Jupyter while learning, add VS Code as your projects grow more complex.

What should I learn after the basics in this guide?

After mastering the basics, your next three priorities in order: First, go deep on Pandas — groupby, merge, reshape, and time series operations. These operations appear in every real project and are the main bottleneck for beginners on real-world data tasks. Second, learn data visualisation properly — work through a Matplotlib tutorial and learn Seaborn for statistical charts. Third, build your first end-to-end project: take a raw dataset, clean it, explore it, ask questions, and present findings. Do not move to machine learning until you feel genuinely confident doing those three things — the machine learning will go much faster once your data handling skills are solid. Our data science career roadmap gives a structured path for everything that follows.

Leave feedback about this

  • Rating

Latest Posts

List of Categories