Python for Data Science
Mastering Python for Beginners in Data Science – Comprehensive Study Notes
Course Overview and Focus
This course is designed for absolute beginners with no prior programming experience. It focuses on three main areas:
Problem solving in computer science: understanding how to formalize a general solution that works for every instance of a problem.
Why Python is chosen, especially for data science problems.
Learning Python itself: starting from installation, variables, and moving progressively through data structures and complex topics.
The course also introduces data science packages (pandas, NumPy, matplotlib) that are fast, fundamental, and powerful for handling large amounts of data – for understanding, visualization, cleaning, and processing.
What is NOT covered: object-oriented programming, exception handling, web development, or general tasks not related to data science.
Problem Solving and Algorithms
What is Problem Solving?
Problems vary in difficulty: some are easy, some difficult, and some impossible (unsolvable). Often the same type of problem must be solved repeatedly (e.g., sorting sales records every eight hours). When the number of instances is large, automation is the optimal choice.
Problem solving deals with formalizing a general solution that works for every instance of a problem. Programming languages (like Python) deal with running that solution on a computer. Python makes the transition from problem solving to a running solution much easier and quicker.
Step-by-Step Solution: The Algorithm
An algorithm is a step-by-step procedure that solves every instance of a given problem. It must be:
Unambiguous
Linked in a sequence
If a step needs more elaboration, it can be broken into further steps
Example: Finding the customer with maximum sales from a list of records:
Start from the first record; focus on the sales column.
Go to each next record and find the record with maximum sales.
If there are multiple records with the same maximum sales, pick the first one (tie-breaking policy).
Focus on the email column of that record.
Write that email address in the priority records.
Repeat this procedure after every eight hours.
This is a general solution – it works for any set of records.
Algorithm Representation: Pseudocode and Flowcharts
Why Not Natural Language?
Natural languages (like English) are expressive but can be ambiguous. To communicate an algorithm precisely, we need a structured, unambiguous way.
Flowcharts
Flowcharts are graphical representations of algorithms. Different shapes represent different actions:
Oval: start/end
Parallelogram: input/output
Rectangle: computation/process
Diamond: decision (if condition)
Arrows: flow of control
Flowcharts are useful for visualizing logic, especially for simple problems.
Pseudocode
Pseudocode is a structured, keyword-based way to express an algorithm without worrying about syntax of a specific programming language. It is:
Concise
Unambiguous
More feasible than flowcharts when the final goal is to convert to actual code (e.g., Python), because the transition from pseudocode to code is easier.
Common keywords: input, output, while, if, else, return, etc. Consistency in keyword usage is important.
Comparison: Flowcharts are more expressive for proof-of-concept, but pseudocode is closer to actual code. Either or both can be used.
Example Problems
Making Tea – Demonstrating Loops and Conditions
The problem: making tea for different people with varying preferences (sugar, milk). The procedure must stay the same; the instances (quantities) change.
Flowchart approach:
Start
Put teabag in cup
Boil water – test if water is boiled; if not, repeat boiling (loop)
Pour boiled water into cup
Loop: while need more sugar – add sugar, test again
Loop: while want milk – add milk, test again
Loop: while need to stir – stir, test again
Tea is ready – serve – end
Pseudocode:
program makeTea
put teabag in cup
while water not boiled
boil water
pour water in cup
while sugar needed
add sugar
while milk needed
add milk
while need to stir
stir
tea is readyKey concept: loop – repeating a procedure until a condition is met.
Searching for the Minimum Value in a List
Given a list of numbers (e.g., [23, -4, 0, 73, -10, 13]), find the minimum value.
Pseudocode:
function search_min_from_list(L, n)
min_value = L[1] // assume first element is min
counter = 2
while counter <= n
v = L[counter]
if v < min_value
min_value = v
increment counter
return min_valueThe algorithm:
Assume the first value is the minimum.
Traverse each subsequent element; if a smaller value is found, update the minimum.
After loop, return the minimum.
Sorting a List (Selection Sort)
Goal: sort a list in ascending order.
Idea: repeatedly find the minimum from the list, copy it to a new list, delete it from the original, and repeat until the original list is empty.
Pseudocode:
function sorted_list(L, n)
L2 = empty list
counter = 1
while counter <= n
(min_value, idx) = search_min_from_list(L, n)
insert min_value into L2
delete L[idx]
n = n - 1
return L2This demonstrates using one algorithm (search for minimum) inside another.
Converting Pseudocode to Python
Python syntax is very close to pseudocode:
Use
defto define functions, with colon at end.Indentation defines blocks (no
end iforend while).List indices start at 0 (not 1) in Python.
whileloops,if-elsestructures, and variable assignments are nearly identical.
Example: The search minimum function in Python:
def search_min_from_list(L, n):
min_value = L[0]
idx = 0
counter = 1
while counter <= n:
v = L[counter]
if v < min_value:
min_value = v
idx = counter
counter += 1
return min_value, idxThe sorting function:
def sorted_list(L, n):
L2 = []
counter = 0
while counter < n:
min_val, idx = search_min_from_list(L, n)
L2.append(min_val)
del L[idx]
n -= 1
return L2Python also provides built-in functions like L.sort() that do this in one line – the purpose of writing the algorithm is to understand the underlying logic.
Python Installation and IDEs
Installing Python
Recommended: install Anaconda distribution, which includes Python, many pre-installed packages, and Jupyter Notebook.
Windows: download executable, follow steps.
Linux/Mac: download version, run bash installer.
After installation, launch Anaconda Prompt and type jupyter notebook to start the Jupyter interface.
What is an IDE?
An IDE (Integrated Development Environment) provides code writing, testing, running, syntax highlighting, auto-completion, debugging, and more in one place.
Popular IDEs for Python/data science:
Jupyter Notebook: Web-based, supports markdown, LaTeX, code, visualization. Very popular in data science community.
PyCharm: Powerful but heavy, good for large projects.
Spyder: Lightweight, open-source, comes with Anaconda, MATLAB-like interface.
For data science, Jupyter Notebook is the most popular choice due to its simplicity, interactivity, and ability to combine code, text, and visuals in one document.
Jupyter Notebook Basics
Launching and Interface
After launching Jupyter, the web interface appears.
Click New → Python 3 to create a new notebook.
The notebook consists of cells. Cells can be Code or Markdown.
Keyboard shortcuts:
Shift+Enter: run cell and move to next.EscthenM: change to Markdown cell.EscthenY: change to Code cell.EscthenF: find and replace.Enter: enter edit mode.
First Python Program: Hello World
In a code cell, type:
print("Hello, world!")Press Shift+Enter to execute. The output appears below.
Markdown Cells
Markdown cells allow you to write headings, descriptions, images, LaTeX equations, etc. Example:
# Heading 1## Heading 2$$E = mc^2$$for a LaTeX equation.
The notebook can be downloaded as PDF, HTML, slides, or .py file.
Variables and Data Types
What is a Variable?
A variable is a symbol (name) that stores data which can be used later. Assignment uses the = sign.
x = 2 # integer
y = 5.0 # float
s = "Hello" # stringPython is dynamically typed: the type of a variable is determined automatically by the value it holds. You do not need to declare the type.
Common Data Types
Integer: whole numbers (e.g.,
2,-5)Float: real numbers with decimal point (e.g.,
3.14,-0.5)Complex: e.g.,
2 + 3jString: sequence of characters (e.g.,
"Python",'data')Boolean:
TrueorFalse
Multiple Assignment
a, b = 4, 5.0 # a is int, b is floatDeleting Variables
del x # removes variable x from memoryAccessing a deleted variable causes an error.
Variable Naming Rules
Must start with a letter or underscore (
_).Cannot start with a digit.
Cannot contain special characters like
@,#,$.Case-sensitive (
Nameandnameare different).Descriptive names improve readability (e.g.,
starting_time_of_course).
Checking Variable Type
type(x) # returns <class 'int'>Operators
Arithmetic Operators
Operator | Description | Example |
|---|---|---|
| Addition |
|
| Subtraction |
|
| Multiplication |
|
| Division (float) |
|
| Floor division (quotient) |
|
| Modulus (remainder) |
|
| Exponentiation |
|
Type Coercion
When mixing types (e.g., int + float), Python automatically promotes to the more general type (float).type(3 + 4.5) → <class 'float'>
Default Variable _
The last computed result that is not assigned to a variable is stored in _ (underscore). Avoid assigning to _ manually.
Boolean Data Type and Comparisons
Boolean Values
Boolean data type has only two values: True and False. Used extensively in decision making.
Boolean Operators
and: returnsTrueonly if both operands areTrue.or: returnsTrueif at least one operand isTrue.not: unary operator that flips the value.
Truth tables:
True and True→True; otherwiseFalseFalse or False→False; otherwiseTruenot True→False;not False→True
Comparison Operators
Operator | Meaning | Example |
|---|---|---|
| Equal to |
|
| Not equal to |
|
| Less than |
|
| Greater than |
|
| Less than or equal to |
|
| Greater than or equal to |
|
Result of a comparison is always a Boolean (True or False).
Combining Comparisons
Comparisons can be combined using and, or, not. Use parentheses to clarify order:
andhas higher precedence thanor.Example:
(x < y) and (z > w) or (p == q)– use parentheses for readability.
Control Flow: Decision Making
if Statement
Executes a block of code when a condition is True.
if condition:
# code blockColon and indentation are required.
if-else
if condition:
# if block
else:
# else blockIf condition is True, the if block runs; otherwise, the else block runs.
if-elif-else
Chain multiple conditions:
if condition1:
# block1
elif condition2:
# block2
else:
# else blockOnly the first true condition's block executes.
Short Form (Ternary Operator)
value = a if condition else bBut for complex logic, use the full if-elif-else structure for readability.
Nested if
An if (or if-else) inside another if:
if condition_outer:
if condition_inner:
# inner if block
else:
# inner else
else:
# outer elseIndentation is critical to define blocks.
Practice Example: Grade Assignment
marks = int(input("Enter marks: "))
if marks >= 85:
grade = "A"
elif marks >= 80:
grade = "A-"
elif marks >= 75:
grade = "B"
elif marks >= 70:
grade = "B-"
else:
grade = "Below Average"
print(grade)Loops
while Loop
Repeats a block as long as a condition is True.
counter = 1
while counter <= n:
print(counter)
counter += 1If condition never becomes False, the loop runs infinitely. Ensure the condition changes within the body.
for Loop
Iterates over a sequence (like a range, list, string, etc.).
for i in range(10): # i from 0 to 9
print(i)range(start, stop, step): generates numbers.
range(5)→ 0,1,2,3,4range(2, 10, 2)→ 2,4,6,8
Loop Control Statements
break: exits the loop immediately.continue: skips the rest of the current iteration and starts the next iteration.
else Clause with Loops
Applies to both while and for. The else block executes if the loop finishes normally (i.e., no break was encountered).
for x in sequence:
if condition:
break
else:
# runs if no break occurredThis is a Python-specific feature; use with caution to avoid confusion.
Nested Loops
A loop inside another loop. Common for multi-dimensional data:
for i in range(3):
for j in range(2):
print(i, j)Functions
Defining a Function
Use def keyword:
def function_name(parameters):
"""docstring (optional)"""
# body
return valueArguments
Positional arguments: order matters.
Keyword arguments: specify parameter name at call time, order becomes irrelevant.
Default values: parameters can have default values; if not provided, default is used.
Variable number of arguments:
*args: captures additional positional arguments as a tuple.**kwargs: captures additional keyword arguments as a dictionary.
Example:
def add_all(*args):
return sum(args)def print_kwargs(**kwargs):
for key, value in kwargs.items():
print(key, value)Return Statement
Returns a value from the function.
Without a return, the function returns
None.Can return multiple values as a tuple:
return a, b, c.
Scope
Variables defined inside a function are local to that function.
Variables defined outside a function are global and can be accessed (but not assigned) inside.
Best practice: pass needed values as arguments rather than relying on global variables.
Modules
A module is a .py file containing functions and variables that can be reused in other scripts.
Use
import module_nameto import the whole module.Use
from module_name import function_nameto import specific parts.Modules can be placed in directories (packages). Use
sys.path.append(path)to add custom module locations.
Strings
Definition
A string is a sequence of characters enclosed in single or double quotes. Both are equivalent.
Indexing and Slicing
Indices start at
0.Negative indices count from the end (
-1is last character).Slicing:
s[start:stop:step]–stopis exclusive.Example:
s = "Hello"→s[1:4]→"ell"
Strings are immutable: you cannot change a character in place. You can create new strings.
Methods
Common string methods (all return new strings, as strings are immutable):
s.strip()– removes leading/trailing whitespace.s.lower()– converts to lowercase.s.upper()– converts to uppercase.s.replace(old, new)– replaces all occurrences.s.split(delimiter)– splits into a list of strings.s.count(sub)– counts occurrences of a substring.s.find(sub)– returns index of first occurrence (or -1).
Membership and Comparison
in/not in: check if a substring is present.Comparison operators work lexicographically (alphabetical order).
Escape Sequences
\n– newline\t– tab\\– backslash\"– double quote inside double-quoted string Use raw strings (r"...") to ignore escape sequences.
Multi-line Strings
Use triple quotes ("""...""" or '''...''').
Data Structures: List, Tuple, Set, Dictionary
Overview Comparison
Feature | List | Tuple | Set | Dictionary |
|---|---|---|---|---|
Ordered | Yes | Yes | No | No (insertion order preserved in Python 3.7+) |
Mutable | Yes | No | Yes (add/remove) | Yes (add/remove) |
Duplicates | Allowed | Allowed | Not allowed | Keys unique; values may duplicate |
Syntax |
|
|
|
|
List
Indexable, mutable, can contain mixed types.
Common methods:
append(),insert(),remove(),pop(),sort(),reverse(),copy().Slicing returns a new list (copy).
Lists can contain any objects, including other lists/dictionaries.
Tuple
Immutable; cannot change elements after creation.
Indexing and slicing same as lists.
Useful for fixed collections (e.g., function return multiple values).
tuple1 + tuple2creates a new tuple (concatenation).
Set
Unordered collection of unique elements.
Supports
add(),remove(),update()(to add multiple),union,intersection, etc.No indexing; use
into check membership.
Dictionary
Key-value pairs; keys must be unique and immutable (strings, numbers, tuples).
Access:
d[key]returns value; assignd[key] = valueto add/update.Methods:
keys(),values(),items(),get(),update(),pop().Very powerful for structured data; basis for pandas.
Copying: Reference vs. Copy
Assignment (
list2 = list1) creates a reference – both variables point to the same object. Changes in one affect the other.To create a separate copy: use
copy()method orlist(my_list).Slicing (
list2 = list1[:]) creates a new copy.
NumPy (Numerical Python)
Import
import numpy as npCreating Arrays
np.array(list_or_tuple)– creates an ndarray.np.arange(start, stop, step)– likerangebut returns array.np.linspace(start, stop, num)– evenly spaced points.np.zeros(shape),np.ones(shape)– arrays of zeros/ones.np.random.rand(d0, d1, ...)– uniform random in [0,1).np.random.randn(d0, d1, ...)– standard normal random.np.random.randint(low, high, size)– random integers.
Array Attributes
ndim– number of dimensions.shape– tuple of sizes per dimension.size– total number of elements.dtype– data type of elements.
Indexing and Slicing
Same syntax as lists, but works for multi-dimensional arrays:
arr[0, :]– first row, all columns.arr[:, 1]– all rows, second column.arr[1:3, 2:4]– submatrix.Slicing returns a view (not a copy). Changes to the slice affect the original. Use
.copy()if you need an independent copy.
Fancy Indexing and Boolean Masking
Array indexing:
arr[[1, 3, 5]]picks rows at those indices; returns a copy.Boolean masking:
arr[arr > 5]returns elements that satisfy condition; returns a copy.Combine conditions with
&(and),|(or),~(not) for arrays.
Universal Functions (ufuncs) – Vectorization
Fast, element-wise operations:
np.add,np.sin,np.cos,np.sqrt,np.exp, etc.Avoid explicit loops on arrays; ufuncs are much faster because they are implemented in C.
Broadcasting
The ability to perform operations on arrays of different shapes. Rules:
Dimensions are compared from the last dimension.
Dimensions must be equal or one of them must be 1.
Scalar values are broadcast to all elements.
Aggregations and Sorting
arr.sum(),arr.mean(),arr.max(),arr.min(),arr.std().np.sort(arr)returns a sorted copy;arr.sort()sorts in-place.np.argsort()returns indices of sorted array.
Speed Example
Summing a large array using Python's built-in
sum()vs.np.sum(): ~100x faster for NumPy's vectorized version.
Reshape
arr.reshape(new_shape)returns a new view (if possible) with the same data in a new shape.Total number of elements must match.
Pandas
Import
import pandas as pdSeries
One-dimensional labeled array (like a dictionary + list).
pd.Series(data, index=index_list).Access by label (
s['a']) or by position usingiloc.
DataFrame
Two-dimensional table (rows and columns). Each column is a Series.
Can be created from dictionary of Series, list of dictionaries, or reading a CSV file.
pd.read_csv('file.csv').
Common DataFrame Operations
df.head(n)– first n rows.df.info()– column types, non-null counts.df.describe()– summary statistics.df['column']– access a column (returns Series).df[['col1', 'col2']]– multiple columns (returns DataFrame).df.iloc[row_index, col_index]– positional indexing.df.loc[row_label, col_label]– label-based indexing.df.drop(columns=['col'], inplace=True)– remove columns.df.rename(columns={'old': 'new'}, inplace=True)– rename.df.groupby('column')– group data; then apply aggregation like.sum(),.mean().df.fillna(value)– fill missing values.df.dropna()– drop rows with missing values.Boolean indexing:
df[df['confirmed'] > 100].
Missing Values
Represented by
NaN(Not a Number) orNone.Common strategies: fill with constant, mean, median; or drop rows/columns.
scikit-learn's
SimpleImputercan be used with different strategies.
Confusion Between Implicit and Explicit Indices
Use
locfor label-based indexing (explicit).Use
ilocfor position-based indexing (implicit, 0-based).
Matplotlib
Import
import matplotlib.pyplot as pltBasic Plotting
plt.plot(x, y, color, linestyle, label)– line plot.plt.scatter(x, y, color, label)– scatter plot.plt.hist(data, bins)– histogram.plt.xlabel('label'),plt.ylabel('label'),plt.title('title').plt.legend()– show legend.plt.show()– display the plot.
Multiple Plots in One Figure
plt.plot(x, y1, label='sin')
plt.plot(x, y2, label='cos')
plt.legend()
plt.show()Customization
Colors:
color='red'or'b'(blue),'g','k', etc.Line styles:
linestyle='--'(dashed),':'(dotted),'-.'(dash-dot).Markers:
marker='o'for circles.
Real Data Example (COVID-19)
Read CSV with
pd.read_csv(), clean columns, fill missing values.Use
groupby('country')to aggregate.Loop over countries and plot trends of confirmed, recovered, deaths over time using scatter plots with different colors.
Customize each plot with title, labels, legend.
Conclusion
This course provided a foundational understanding of Python programming with a focus on data science. Key takeaways:
Problem solving is about creating general, step-by-step algorithms.
Python is a beginner-friendly, powerful language for data science, with a rich ecosystem of packages.
Data structures (list, tuple, set, dictionary) are essential for managing data.
NumPy enables fast numerical computations with vectorized operations.
Pandas simplifies data manipulation and analysis, especially with tabular data.
Matplotlib allows quick and customizable visualizations for data exploration.
These skills prepare you for more advanced topics in machine learning, deep learning, and big data analytics. Continue practicing with real datasets and exploring packages like scikit-learn, TensorFlow, and PyTorch.

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