? Python for Data Science
? Python for Data Science
🔰 Introduction
Course assumes some coding experience.
Covers Python syntax, variables, arithmetic, and basic functions.
📌 Python Basics
✅ Variable Assignment
python
CopyEdit
spam_amount = 0
= is the assignment operator.
No need to declare type or initialize variables beforehand.
✅ Print Function
python
CopyEdit
print(spam_amount)
print() outputs to console.
✅ Comments
python
CopyEdit
# This is a comment
✅ Reassignment and Arithmetic
python
CopyEdit
spam_amount = spam_amount + 4
You can reassign variables using arithmetic expressions.
🔁 Conditional Statements
python
CopyEdit
if spam_amount > 0:
print("But I don't want ANY spam!")
if starts a code block (indentation matters!).
Colons : signal the start of an indented block.
🔢 Data Types
python
CopyEdit
type(0) → int
type(19.95) → float
int: whole numbers
float: decimals
type() checks data type
➕ Arithmetic Operators
+ Addition a+b→7
- Subtraction a - b → 3
Multiplicatio
* a * b → 10
n
Floor
// a // b → 2 Int
Division
% Modulus a%b→1
** Exponentiati a ** b → 25
Operat Example (a = 5, Resul
Name
or b = 2) t
on
-a Negation -a → -5
🛠 Built-in Functions
min(a, b, c): Smallest value
max(a, b, c): Largest value
abs(x): Absolute value
int(): Converts to integer
float(): Converts to float
python
CopyEdit
int('807') + 1 → 808
----------
Defining Functions
Syntax:
python
CopyEdit
def function_name(parameters):
# block of code
return result
Example:
python
CopyEdit
def least_difference(a, b, c):
return min(abs(a-b), abs(b-c), abs(a-c))
📄 Docstrings
Description added just after function definition using triple quotes """.
Helps describe what the function does.
Example:
python
CopyEdit
def greet():
"""This function prints a greeting."""
print("Hello!")
help(greet) will now show the docstring.
🧩 Default Arguments
Provide default values to parameters:
python
CopyEdit
def greet(who="Colin"):
print("Hello,", who)
Can override defaults by passing arguments:
python
CopyEdit
greet("Kaggle") # Output: Hello, Kaggle
🔁 Functions as Arguments
You can pass functions as arguments to other functions.
Example:
python
CopyEdit
def call(fn, arg):
return fn(arg)
Higher-order functions: functions that take other functions as inputs or
return them.
------------
🟩 Booleans in Python
bool type has two values: True and False
Created by:
python
CopyEdit
x = True
type(x) # <class 'bool'>
🟨 Comparison Operators
Operati
Meaning
on
a == b a equals b
a != b a not equal to b
Examples:
python
CopyEdit
'3' == 3 # False
3.0 == 3 # True
🟥 Boolean Conversion
python
CopyEdit
bool(1) # True
bool(0) # False
bool("hi") # True
bool("") # False
Non-zero numbers and non-empty strings/lists → True
0, "", [], etc. → False
Used implicitly:
python
CopyEdit
if 0:
print("won’t run")
elif "spam":
print("spam") # This prints
✅ Lists
Definition: Ordered, mutable collections.
Creation:
python
CopyEdit
primes = [2, 3, 5, 7]
Types: Can contain any data type, even other lists.
Indexing:
o list[0] – first element
Slicing:
o list[start:end] – elements from start to end-1
Mutability:
o Lists can be modified using assignment:
python
CopyEdit
planets[3] = 'Malacandra'
planets[:3] = ['Mur', 'Vee', 'Ur']
Useful Functions:
o len(), sorted(), sum(), min(), max()
Common Methods:
o append() – adds to the end
📦 Tuples
Definition: Ordered, immutable collections.
Creation:
python
CopyEdit
t = (1, 2, 3)
t = 1, 2, 3 # same
Immutability:
o Cannot change elements (t[0] = 100 → ❌ TypeError)
🔁 Loops Overview
Loops allow repeated execution of code.
🪐 for Loop
python
CopyEdit
planets = ['Mercury', 'Venus', 'Earth', ...]
for planet in planets:
print(planet, end=' ')
Iterates over items in any iterable: list, tuple, string, etc.
Structure: for <var> in <iterable>:
# String
s = 'someText'
for char in s:
if char.isupper():
print(char, end='')
Works with tuples, strings, or anything that supports iteration.
🔢 range()
python
CopyEdit
for i in range(5):
print(i)
Produces numbers from 0 to n-1
Can also use range(start, stop, step)
🔁 while Loop
python
CopyEdit
i=0
while i < 10:
print(i)
i += 1
Repeats while the condition is True.
🔄 List Comprehensions
Compact way to create lists.
python
CopyEdit
squares = [n**2 for n in range(10)]
# Equivalent to:
squares = []
for n in range(10):
squares.append(n**2)
With condition:
python
CopyEdit
short_planets = [planet for planet in planets if len(planet) < 6]
With transformation + condition:
python
CopyEdit
[planet.upper() + '!' for planet in planets if len(planet) < 6]
Strings
Definition & Syntax
Can be enclosed in single or double quotes:
python
CopyEdit
'hello' == "hello"
Use escaping (\) to include quotes or special characters:
\', \", \\, \n (newline)
Multi-line & Print
Triple-quoted strings allow literal newlines:
python
CopyEdit
"""line1
line2"""
print(..., end='') prevents auto-newline
Sequence behavior
Support indexing, slicing, len(), iteration
Immutable – cannot change in place
Common methods
.upper(), .lower()
.index(sub), .startswith(prefix), .endswith(suffix)
Splitting & Joining
.split() → list of words
sep.join(list) → string with sep between items
Formatting
Concatenate with +, but better:
python
CopyEdit
"{} weighs about {:.2} kg".format(var, num)
Supports positional formatting, number formatting, commas, percent,
exponents
Dictionaries
Definition
Key→value mappings:
python
CopyEdit
d = {'one': 1, 'two': 2}
Access & Modify
Access via d[key]; add/change via assignment:
python
CopyEdit
d['three'] = 3
Comprehensions
Create dicts from iterables:
python
CopyEdit
{p: p[0] for p in planets}
Membership & Iteration
key in d checks presence
Looping iterates keys:
python
CopyEdit
for k in d:
print(k, d[k])
Convenient methods
.keys(), .values(), .items() for keys, values, and key-value pairs
Use .items() to loop with unpacking:
python
CopyEdit
for k, v in d.items():
...
🚀 Imports in Python
Standard vs. external libraries:
o Standard library modules (like math) are built-in.
Import syntax:
python
CopyEdit
import math
import math as mt # alias
from math import log, pi # specific names
from math import * # discouraged: can cause name conflicts
Why avoid import *:
o Overwrites names from other modules
Submodules:
o Modules can contain other modules:
python
CopyEdit
numpy.random.randint(...)
✨ Operator Overloading
Python allows custom behavior for operators (+, <, in, etc.) via special
methods like __add__, __lt__, __contains__.
Example differences:
o Lists: [1,2,3] + 10 → error