🧠 Why Python Programming for Data Science?
Python is one of the most loved languages for data science because:
- It’s simple and readable, even for beginners
- It has a massive library ecosystem (NumPy, pandas, matplotlib)
- It allows interactive coding through tools like Jupyter Notebooks
- It has a huge global community that supports and contributes to its development
Want to learn about Data Science in detail? Follow this tutorial.
🔤 Python Basics Refresher (Before Jumping to Data Science)
- Dynamic Typing – You don’t need to declare variable types.
x = 10 # Python knows x is an integer
- Indentation – Python uses indentation instead of curly braces to structure code.
if x > 5: print("Greater than 5")
- Simple Syntax – Clean and easy to write/read.
name = "Kunal" print("Hello", name)
🔧 Must-Know Libraries for Data Science
Library | Purpose |
---|---|
NumPy | Numerical computing, arrays |
pandas | Data manipulation and analysis |
matplotlib | Basic data visualization |
seaborn | Statistical visualizations (built on matplotlib) |
scikit-learn | Machine learning |
TensorFlow , PyTorch | Deep learning frameworks |
Statsmodels | Statistical testing and modeling |
XGBoost | High-performance gradient boosting |
🧪 Why JupyterLab and Anaconda?
In case you don’t have Anaconda installed so watch this tutorial below that will guide you on how to install Anaconda on Windows and Mac both:
Tool | Why Use It? |
---|---|
Jupyter Notebook | Lets you write and run Python code in chunks. Ideal for learning and testing. |
JupyterLab | More advanced version with multi-panel layout. Ideal for full projects. |
Anaconda | One-click installer that gives Python + all major data science libraries. |
✅ You can visualize graphs, see outputs below code cells, and even export your work to PDF or HTML.
💼 Real-World Companies Using Python
Company | Use Case |
---|---|
Netflix | Content recommendations and streaming optimization |
Spotify | Music recommendations using machine learning |
Scalable backend development | |
Dropbox | Cloud storage with reliable Python infrastructure |
Uber | Real-time pricing and ride-matching using data science |
🧑🏫 Final Summary for You:
“Python is the backbone of modern data science. Its simplicity, flexibility, and huge support ecosystem make it the go-to tool for analyzing data, building models, and creating powerful applications.”
📘 Python Basics: Variables, Data Types & Typecasting (For Data Science Beginners)
When learning Python for Data Science, mastering variables, data types, and typecasting is essential. Here’s a beginner-friendly guide to help you understand it clearly.
✅ What Are Variables?
Think of variables like labeled containers that store data. You don’t need to declare the type in advance—Python figures it out on its own.
name = "Alice"
age = 25
is_student = True
name
holds a string (text)age
holds a numberis_student
holds a boolean (True/False)
📊 Common Python Data Types
Type | Example | Meaning |
---|---|---|
int | 10, -5 | Integer (whole) numbers |
float | 3.14, -0.5 | Decimal numbers |
str | “hello” | Text (string) |
bool | True, False | Boolean values (yes/no, on/off) |
list | [1, 2, 3] | Ordered, editable collection |
tuple | (1, 2, 3) | Ordered, unchangeable collection |
dict | {“a”: 1} | Key-value pairs |
🔄 What is Typecasting?
Typecasting means converting one data type into another using Python’s built-in functions.
Example Conversions:
x = int("10") # "10" → 10 (string to int)
y = str(25) # 25 → "25" (int to string)
z = int(3.9) # 3.9 → 3 (float to int, truncates not rounds)
lst = list("abc") # "abc" → ['a', 'b', 'c'] (string to list)
⚠️ Be careful: not all conversions work.
("hello") # ❌ Will raise a ValueError
💡 Quick Tips:
- Use
type(variable)
to check the data type. - Always ensure compatibility before typecasting to avoid errors.
🧵 String & String Methods in Python – Beginner’s Guide
In Python, strings are one of the most commonly used data types, especially in data science, web scraping, automation, and more. This lesson dives into what strings are and the most useful string methods for beginners.
🔤 What is a String?
A string is a sequence of characters enclosed in:
- Single quotes →
'Hello'
- Double quotes →
"Hello"
Example:
name = "Alice"
greeting = 'Hello'
📜 Multiline Strings
To write strings that span multiple lines, use triple quotes:
message = """This is
a multiline
string."""
🧮 String Indexing and Slicing
- Python indexes start from 0
- You can access individual characters or a slice (subset) of a string
Example:
text = "Python"
text[0] # 'P'
text[-1] # 'n'
text[0:2] # 'Py'
text[:3] # 'Pyt'
text[3:] # 'hon'
🚫 String Immutability
Strings in Python are immutable. This means once created, they can’t be changed.
Wrong:
text[0] = 'J' # ❌ This will throw an error
If you want to “change” a string, create a new one.
🧰 Common String Methods
Method | Description |
---|---|
str.lower() | Converts to lowercase |
str.upper() | Converts to uppercase |
str.strip() | Removes whitespace |
str.replace(old, new) | Replaces text |
str.split(sep) | Splits string into list |
str.join(list) | Joins list into string |
str.find(sub) | Finds first index of substring |
str.count(sub) | Counts occurrences of substring |
str.startswith() | Checks if string starts with value |
str.endswith() | Checks if string ends with value |
str.isdigit() | Checks if all chars are digits |
str.isalpha() | Checks if all chars are alphabets |
str.isalnum() | Checks if all chars are alphanumeric |
🧪 Examples
"hello".upper() # 'HELLO'
" Hello ".strip() # 'Hello'
"hello world".split() # ['hello', 'world']
"-".join(["2025", "04", "14"]) # '2025-04-14'
"python".find("th") # 2
🔧 String Formatting (f-Strings)
Use f-strings to create dynamic messages easily:
name = "Alice"
age = 30
f"Hello, {name}. You are {age} years old."
# 'Hello, Alice. You are 30 years old.'
💡 Quick Recap:
- Strings are powerful text containers.
- They support indexing, slicing, and immutability.
- Use string methods to clean, search, or format data.
- f-Strings make it super easy to embed variables inside text.
📋 What Are Operators in python programming for data science?
Operators are special symbols used to perform operations on variables and values in Python. They help you manipulate data and make decisions in your code.
1️⃣ Arithmetic Operators
Used for basic mathematical calculations.
Operator | Description | Example (a=10, b=5) | Output |
---|---|---|---|
+ | Addition | a + b | 15 |
- | Subtraction | a - b | 5 |
* | Multiplication | a * b | 50 |
/ | Division | a / b | 2.0 |
// | Floor Division | a // b | 2 |
% | Modulus (remainder) | a % b | 0 |
** | Exponentiation | a ** b | 100000 |
2️⃣ Comparison Operators
Compare values and return True
or False
.
Operator | Description | Example (a=10, b=5) | Output |
---|---|---|---|
== | Equal to | a == b | False |
!= | Not equal to | a != b | True |
> | Greater than | a > b | True |
< | Less than | a < b | False |
>= | Greater than or equal to | a >= b | True |
<= | Less than or equal to | a <= b | False |
3️⃣ Logical Operators
Combine multiple conditions.
Operator | Description | Example (x=True, y=False) | Output |
---|---|---|---|
and | Both True | x and y | False |
or | Either True | x or y | True |
not | Negation | not x | False |
4️⃣ Bitwise Operators
Perform operations at the binary level.
Operator | Description | Example (a=5, b=3) | Output |
---|---|---|---|
& | AND | a & b | 1 |
` | ` | OR | `a |
5️⃣ Assignment Operators
Assign values to variables with operations.
Operator | Example (a=10) | Equivalent |
---|---|---|
= | a = 5 | a = 5 |
+= | a += 5 | a = a + 5 |
-= | a -= 5 | a = a - 5 |
*= | a *= 5 | a = a * 5 |
/= | a /= 5 | a = a / 5 |
//= | a //= 5 | a = a // 5 |
%= | a %= 5 | a = a % 5 |
**= | a **= 5 | a = a ** 5 |
6️⃣ Membership & Identity Operators
Check for existence and object identity.
Operator | Description | Example (lst=[1,2,3], x=2 ) | Output |
---|---|---|---|
in | Present in sequence | x in lst | True |
not in | Not present | x not in lst | False |
is | Same object | a is b | False |
is not | Different object | a is not b | True |
Hope you have understood about python programming for data science
🧠 Taking Input from the User in Python – Easy Explanation
In Python, the input()
function is used to collect information from the user. It allows you to make your programs interactive. For example, you can ask the user their name, age, or any data—and then use that info in your code.
✅ Basic Syntax:
name = input("Enter your name: ")
print("Hello", name)
input()
displays the prompt message inside the quotation marks.- Whatever the user types is stored as a string.
🔁 Type Conversion (Typecasting)
Since input()
always returns data as string, we need to convert it to other types like integers or floats when needed.
✅ Example:
age = int(input("Enter your age: ")) # Converts input to integer
price = float(input("Enter the price: ")) # Converts input to float
int()
converts input into whole numbers.float()
converts input into decimal numbers.
If the user types something that cannot be converted (e.g. letters instead of numbers), Python will throw an error.
🔎 Key Notes for Students:
input()
is always a string by default.- Use
int()
orfloat()
for numeric inputs. - This helps make programs dynamic and user-friendly.
- Always consider using type conversion when working with numbers.
👨🏫 Real-World Example:
name = input("What’s your name? ")
age = int(input("How old are you? "))
print(f"{name} will be {age + 1} years old next year!")
🎯 Operator Precedence in Python: What Runs First?
When you’re solving a math problem in Python, how does Python know which part to calculate first?
Just like in school math, Python follows a specific order of operations known as PEMDAS:
✅ What is PEMDAS?
PEMDAS stands for:
- Parentheses
( )
– Always done first. - Exponents
**
– Powers come next. - Multiplication
*
, Division/
, Floor Division//
, and Modulus%
– Left to right. - Addition
+
, Subtraction-
– Done last, from left to right.
🧠 Why Operator Precedence Matters?
If you write something like:
result = 10 + 2 * 3
Python first multiplies 2 * 3 = 6
, then adds 10 + 6 = 16
.
But if you add parentheses:
result = (10 + 2) * 3
Python calculates 10 + 2 = 12
first, then 12 * 3 = 36
.
🧪 Examples You Can Show Students:
# Without parentheses
result = 10 + 2 * 3 # Output: 16
# With parentheses
result = (10 + 2) * 3 # Output: 36
# Right-to-left for exponentiation
result = 2 ** 3 ** 2 # 3**2 = 9, then 2**9 = 512
💡 Quick Summary for Students:
- Always use parentheses to control what runs first.
- Exponentiation
**
is right-associative, meaning it runs from right to left. - Multiplication/Division/Modulus run before Addition/Subtraction.
🧠 Understanding if
, else
, and elif
in Python
Conditional statements are used to make decisions in your Python code. Just like how we decide things in real life (“if it rains, I’ll take an umbrella”), Python also allows you to execute different code based on whether a condition is true or false.
✅ Basic if
Statement
The if
statement runs a block of code only if the condition is true.
x = 10
if x > 5:
print("x is greater than 5")
- If
x > 5
is true, the print statement runs. - If it’s false, nothing happens.
🔁 if-else
Statement
When you want to handle both true and false cases, use if-else
.
x = 3
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")
- If
x > 5
, the first message is printed. - Otherwise, the
else
block executes.
🔄 if-elif-else
Statement
Use this when you have multiple conditions to check.
x = 5
if x > 10:
print("x is greater than 10")
elif x > 5:
print("x is greater than 5 but not more than 10")
elif x == 5:
print("x is exactly 5")
else:
print("x is less than 5")
- Conditions are checked from top to bottom.
- The first true condition executes, and the rest are skipped.
📊 Real-Life Use Case in Data Science
Example 1: Categorizing Data
age = 25
if age < 18:
category = "Minor"
elif age < 65:
category = "Adult"
else:
category = "Senior Citizen"
print("Category:", category)
You can use such logic to group users based on age.
Example 2: Conditional Logic on DataFrame
import pandas as pd
data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Score': [85, 40, 75]}
df = pd.DataFrame(data)
df['Result'] = df['Score'].apply(lambda x: 'Pass' if x >= 50 else 'Fail')
print(df)
This is extremely useful for filtering and labeling data automatically.
📝 Summary for Students
if
: Runs when the condition isTrue
.if-else
: Adds an alternative when condition isFalse
.if-elif-else
: Lets you check multiple conditions in sequence.- Essential in data cleaning, filtering, and decision-making.
🧠 What is match-case
in Python?
Now what is match-case
Python Programming For Data Science
Introduced in Python 3.10, match-case
is Python’s version of switch-case from other languages. It allows pattern matching to simplify conditional branching — making code easier to read and manage.
✍️ Syntax Example:
def http_status(code):
match code:
case 200:
return "OK"
case 400:
return "Bad Request"
case 404:
return "Not Found"
case 500:
return "Internal Server Error"
case _:
return "Unknown Status"
✅ case _:
acts like a default fallback if no other case matches.
💡 Features of match-case:
- Clean alternative to long
if-elif-else
chains. case _
works as a default case.- Supports patterns like literals, variables, and structural patterns (e.g., tuples).
📦 Real Use Case: Matching Data Structures
point = (3, 4)
match point:
case (0, 0):
print("Origin")
case (x, 0):
print(f"X-Axis at {x}")
case (0, y):
print(f"Y-Axis at {y}")
case (x, y):
print(f"Point at ({x}, {y})")
This pattern checks for a point’s location and provides a response based on its position.
📝 Blog Notes for Students:
match-case
is only available in Python 3.10 and above.- Helps avoid messy nested conditions.
- It’s excellent for checking HTTP status codes, menu selections, input categories, or anything with fixed outcomes.
- Great for clean readable code, especially in data processing or automation tasks.
- Always include a
case _:
block to handle unknown or unexpected values.
🧵 String Formatting in Python: A Beginner’s Guide to format()
and f-Strings
In Python, strings are everywhere—from printing messages to displaying results. When it comes to inserting values into strings, Python gives you powerful formatting tools. In this guide, you’ll learn two popular ways:
- Using
.format()
method - Using f-Strings (Recommended)
📌 1. Using .format()
Method
You can insert variables inside a string using curly {}
brackets and the .format()
method.
✍️ Example:
name = "Alice"
age = 25
print("My name is {} and I am {} years old.".format(name, age))
➡️ Output: My name is Alice and I am 25 years old.
🔄 Positional vs Keyword Arguments:
print("{} is learning {}".format("Alice", "Python")) # Positional
print("{name} is learning {language}".format(name="Alice", language="Python")) # Keyword
✅ 2. Using f-Strings (Python 3.6+)
f-Strings are cleaner, faster, and more readable. Just add an f
before the string and insert variables inside {}
.
✍️ Example:
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
➡️ Output: My name is Alice and I am 25 years old.
🧮 Expressions Inside f-Strings
You can also run expressions directly inside {}
:
a = 5
b = 10
print(f"Sum of {a} and {b} is {a + b}")
➡️ Output: Sum of 5 and 10 is 15
🔢 Formatting Numbers
Control how numbers appear using format specifiers:
pi = 3.14159
print(f"Pi rounded to 2 decimal places: {pi:.2f}")
➡️ Output: Pi rounded to 2 decimal places: 3.14
📐 Padding and Alignment
Align text using :<
, :>
, and :^
inside f-Strings.
print(f"{'Python':<10}") # Left-align
print(f"{'Python':>10}") # Right-align
print(f"{'Python':^10}") # Center-align
➡️ Output:
Python
Python
Python
💡 Here 10
is the total space, and the symbols decide alignment.
🧠 Why Use f-Strings?
- Cleaner syntax
- Easier to read
- Supports inline expressions
- Great for formatting numbers and text
🎓 Summary for Students
- Use
.format()
when working with older Python versions. - Prefer
f-strings
for simplicity and performance. - Practice inserting variables and expressions into strings.
- Use formatting for clean output in reports, dashboards, etc.
🌀 Loops in Python: Explained for Beginners
Loops are a powerful feature in Python that let you execute a block of code repeatedly. Whether you’re processing a list of data, printing numbers, or automating a task, loops are essential in every Python program.
Python offers two main types of loops:
for
loopwhile
loop
Let’s explore both with examples and tips.
🔁 1. For Loop
A for
loop is used when you want to iterate over a sequence (like a list, tuple, or string).
Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
📌 Output:
apple
banana
cherry
You can also loop over a sequence of numbers using the range()
function:
for i in range(3):
print(i)
📌 Output:
0
1
2
🔄 2. While Loop
A while
loop keeps running as long as the condition is True
.
Example:
count = 0
while count < 3:
print(count)
count += 1
📌 Output:
0
1
2
⛔ 3. Loop Control Statements
Sometimes, you need to control how and when a loop should stop or skip. Here’s how:
Statement | Description |
---|---|
break | Exits the loop completely |
continue | Skips the current iteration and moves to the next |
pass | Does nothing; used as a placeholder |
Example using break
:
for i in range(5):
if i == 3:
break
print(i)
📌 Output:
0
1
2
✨ Bonus Tip: Use Cases of Loops
- ✅ Repeating actions (e.g., sending emails in bulk)
- ✅ Reading files line-by-line
- ✅ Processing each item in a dataset
- ✅ Performing automation tasks
✅ Summary
- Use
for
loops for known number of iterations or over collections. - Use
while
loops for uncertain or conditional repetition. break
,continue
, andpass
offer fine control over your loops.
List and List Methods in Python Programming for Data Science
In Python, a list is an ordered, mutable collection used to store multiple items. Lists are incredibly flexible and powerful — you can store different data types (integers, strings, booleans, even other lists) in a single list.
✅ Creating a List
# Empty list
my_list = []
# List with integers
numbers = [1, 2, 3, 4, 5]
# List with mixed data types
mixed_list = [1, "Hello", 3.14, True]
🛠️ Common List Methods
Method | Description | Example |
---|---|---|
append(x) | Adds x to the end of the list | my_list.append(10) |
extend(iterable) | Adds all elements from the iterable | my_list.extend([6, 7, 8]) |
insert(index, x) | Inserts x at the given index | my_list.insert(2, "Python") |
remove(x) | Removes the first occurrence of x | my_list.remove(3) |
pop([index]) | Removes and returns item at index (last if not given) | my_list.pop(2) |
index(x) | Returns the index of the first occurrence of x | my_list.index(4) |
count(x) | Counts how many times x appears | my_list.count(2) |
sort() | Sorts the list in ascending order | my_list.sort() |
reverse() | Reverses the order of the list | my_list.reverse() |
copy() | Returns a shallow copy of the list | new_list = my_list.copy() |
clear() | Empties the list | my_list.clear() |
🧪 Example Usage
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
print(fruits)
# Output: ['apple', 'banana', 'cherry', 'orange']
fruits.sort()
print(fruits)
# Output: ['apple', 'banana', 'cherry', 'orange']
💡 Quick Tips
- Lists are mutable — you can change, delete, and add elements anytime.
- Always use
append()
when adding one item andextend()
for multiple items. - Use
copy()
if you want to duplicate the list without changing the original. pop()
is great for removing items and using their values right away.
🧠 Tuples and Tuple Methods in Python — Beginner Notes
Tuples are one of Python’s basic data structures. They are just like lists but immutable — which means you can’t change their values once created. This makes them super useful for fixed data, like days of the week, coordinates, or records.
✅ What is a Tuple?
A tuple is an ordered, immutable collection of items. Think of it like a list, but locked after creation.
# Creating a tuple
my_tuple = (1, 2, 3, 4)
✔ Tuples are written using parentheses ()
✔ They can contain mixed data types (numbers, strings, booleans)
🛠 Creating Tuples
empty_tuple = () # Empty tuple
numbers = (1, 2, 3, 4, 5) # Tuple with integers
mixed_tuple = (1, "Hello", 3.14, True) # Mixed data types
single_element = (42,) # Single element tuple - must have a comma!
Note: If you forget the comma in a one-item tuple, Python won’t treat it as a tuple.
📚 Tuple Methods
Tuples have fewer methods than lists because they’re immutable.
Method | Description | Example |
---|---|---|
count(x) | Returns how many times x appears in the tuple | my_tuple.count(2) |
index(x) | Returns the index of the first occurrence of x | my_tuple.index(3) |
⚡ Tuple Characteristics
- 🔒 Immutable: You can’t add, remove, or change elements once defined.
- 🚀 Faster than lists: Tuple access is faster because of immutability.
- 🧠 Can be used as dictionary keys: Lists can’t be used as keys, but tuples can.
🔍 Accessing Tuple Elements
You can access tuple elements just like lists — using indexing and slicing.
my_tuple = (10, 20, 30, 40)
print(my_tuple[1]) # Output: 20
print(my_tuple[1:3]) # Output: (20, 30)
📦 Tuple Packing and Unpacking
Packing = putting multiple values into one tuple.
Unpacking = extracting them back into variables.
# Packing
person = ("Alice", 25, "Engineer")
# Unpacking
name, age, profession = person
print(name) # Alice
print(age) # 25
🕒 When to Use Tuples?
Use a tuple when:
- ✅ You need an unchangeable set of items (e.g. days of the week)
- ✅ You want a faster alternative to lists
- ✅ You’re storing heterogeneous data (like records)
🔹 Sets & Set Methods in Python – Beginner’s Notes
🔍 What is a Set in Python?
A set is:
- Unordered: No indexing or slicing.
- Mutable: You can add/remove items.
- Unique: No duplicate values allowed.
It’s perfect when you want to store a group of distinct items—like tags, IDs, or filtered results.
🛠 Creating a Set
empty_set = set()
numbers = {1, 2, 3, 4, 5}
mixed_set = {1, "Hello", 3.14, True}
unique_numbers = set([1, 2, 2, 3, 4, 4, 5])
Output:
{1, 2, 3, 4, 5}
— duplicates removed automatically!
✅ Common Set Methods
Method | Description | Example |
---|---|---|
add(x) | Adds item x | my_set.add(10) |
update(iter) | Adds multiple items from iterable | my_set.update([6, 7, 8]) |
remove(x) | Removes x (raises error if not found) | my_set.remove(3) |
discard(x) | Removes x (no error if not found) | my_set.discard(3) |
pop() | Removes and returns a random element | my_set.pop() |
clear() | Empties the entire set | my_set.clear() |
copy() | Creates a shallow copy of the set | new = my_set.copy() |
🧮 Set Operations
Operation | Description | Example |
---|---|---|
union(set2) | Combines all unique elements | set1.union(set2) |
intersection(set2) | Common elements in both sets | set1.intersection(set2) |
difference(set2) | Elements in set1 not in set2 | set1.difference(set2) |
symmetric_difference(set2) | Elements in either set, but not both | set1.symmetric_difference(set2) |
issubset(set2) | Returns True if set1 is subset of set2 | set1.issubset(set2) |
issuperset(set2) | Returns True if set1 is superset of set2 | set1.issuperset(set2) |
🔄 Example Usage
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
print(set1 | set2) # Union → {1, 2, 3, 4, 5, 6}
print(set1 & set2) # Intersection → {3, 4}
print(set1 - set2) # Difference → {1, 2}
print(set1 ^ set2) # Symmetric Difference → {1, 2, 5, 6}
📌 Key Properties of Sets
- ❌ No indexing or slicing
- ✅ Duplicates removed automatically
- 🔄 Mutable – you can update it anytime
💡 When to Use Sets?
- You want a collection of unique items
- You need fast membership checks
- You want to eliminate duplicates from data
📘 Python Dictionary & Dictionary Methods – Quick Notes for Students
In Python, a dictionary is a powerful, flexible, and efficient data structure used to store data in key-value pairs. This lesson teaches how to create, access, and manipulate dictionaries using built-in methods.
🧱 What is a Dictionary?
- A dictionary is an unordered, mutable collection of data in key-value pairs.
- Python 3.7+ maintains insertion order.
- Keys must be unique and immutable (like strings, numbers, or tuples).
- Values can be of any data type and even be mutable (like lists, dicts).
🛠️ Creating a Dictionary
# Empty dictionary
empty_dict = {}
# Dictionary with data
student = {
"name": "Alice",
"age": 25,
"grade": "A"
}
# Using dict() constructor
person = dict(name="John", age=30, city="New York")
🔍 Accessing Elements
# Access using key
print(student["name"]) # Output: Alice
# Access using get (to avoid KeyError)
print(student.get("age")) # Output: 25
print(student.get("height", "Not Found")) # Output: Not Found
🔄 Common Dictionary Methods
Method | Description | Example |
---|---|---|
keys() | Returns all keys | student.keys() |
values() | Returns all values | student.values() |
items() | Returns key-value pairs as tuples | student.items() |
get(key, default) | Returns value for key or default if not found | student.get("age", 0) |
update(dict2) | Merges another dict into this one | student.update({"age": 26}) |
pop(key) | Removes key and returns value | student.pop("grade") |
popitem() | Removes last inserted item | student.popitem() |
setdefault() | Returns key value or sets it to default | student.setdefault("city", "Unknown") |
clear() | Removes all items | student.clear() |
copy() | Creates shallow copy | new_dict = student.copy() |
🧪 Practical Example
student = {"name": "Alice", "age": 25, "grade": "A"}
# Add new key-value pair
student["city"] = "New York"
# Update existing value
student["age"] = 26
# Remove item
student.pop("grade")
# Iterate over dictionary
for key, value in student.items():
print(key, ":", value)
🖨️ Output:
name : Alice
age : 26
city : New York
🔁 Dictionary Comprehension
# Create dictionary with squares
squares = {x: x**2 for x in range(1, 6)}
print(squares) # Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
🧠 Key Properties Recap
- 🔄 Mutable: You can change or update values.
- 🔑 Unique Keys: No duplicates allowed for keys.
- 🧺 Efficient: Lookup and updates are fast.
- 🗂️ Ordered (from Python 3.7+): Preserves insertion order.
🧾 Summary Table: List vs Set vs Tuple vs Dictionary
Feature | List | Set | Tuple | Dictionary |
---|---|---|---|---|
Syntax | [1, 2, 3] | {1, 2, 3} | (1, 2, 3) | {"name": "Alice", "age": 25} |
Ordered? | ✅ Yes | ❌ No | ✅ Yes | ✅ (Yes since Python 3.7) |
Duplicates Allowed? | ✅ Yes | ❌ No | ✅ Yes | ✅ Keys unique, values can repeat |
Mutable? | ✅ Yes | ✅ Yes | ❌ No | ✅ Yes |
Indexing? | ✅ Yes | ❌ No | ✅ Yes | ✅ Yes (by key) |
Use Case | Ordered collection with access | Unique values only | Read-only ordered collection | Key-value pairs (like a real-life dictionary) |
Real-Life Example | Shopping list 🛒 | Unique fruits 🍎🍊🍌 | Coordinates (x, y) 📍 | Student record 📒 |
🧑🏫 Beginner-Friendly Notes (Perfect for Students)
1. ✅ List
- Like a basket of items you can rearrange or edit.
- You can add, remove, or change items.
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple
2. 🧹 Set
- Like a basket where no duplicates are allowed and order doesn’t matter.
- Good for checking if something exists.
unique_fruits = {"apple", "banana", "apple"}
print(unique_fruits) # {'apple', 'banana'}
3. 🧊 Tuple
- Like a sealed box — you can look, but not change what’s inside.
- Great for fixed data like coordinates or constant settings.
coordinates = (10, 20)
print(coordinates[1]) # 20
4. 📖 Dictionary
- Like a real dictionary: Each word (key) has a meaning (value).
- Useful for structured data.
student = {"name": "Alice", "age": 25}
print(student["name"]) # Alice
🧠 Visual Analogy:
Object | Analogy |
---|---|
List | Like a queue of people (ordered) |
Set | Like a guest list (no repeats) |
Tuple | Like your birthdate (unchangeable) |
Dictionary | Like a contact book 📒 |
🧰 Bonus Cheat Sheet:
# List
l = [1, 2, 3]
# Set
s = {1, 2, 3}
# Tuple
t = (1, 2, 3)
# Dictionary
d = {"name": "Alice", "age": 25}
🗂️ File Handling in Python (Student Notes)
What is File Handling?
File handling allows Python to interact with files stored on your computer: read them, write into them, or delete them.
File handing is again a very important concept for python programming for data science.
✍️ Syntax to Open a File
file = open("filename.txt", "mode")
"filename.txt"
– name of the file."mode"
– how the file should be opened ("r"
,"w"
,"a"
, etc.)
📄 File Modes
Mode | Purpose |
---|---|
'r' | Read (file must exist) |
'w' | Write (creates new or overwrites) |
'a' | Append (adds at end of file) |
'x' | Create (fails if file exists) |
'b' | Binary mode for non-text files (like images) |
't' | Text mode (default) |
📖 Reading Files
# Read entire file
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()
# Read one line
file = open("example.txt", "r")
line1 = file.readline()
print(line1)
file.close()
# Read all lines as a list
file = open("example.txt", "r")
lines = file.readlines()
print(lines)
file.close()
✏️ Writing Files
# Overwrite existing content
file = open("example.txt", "w")
file.write("Hello, World!")
file.close()
# Write multiple lines
lines = ["Hello\n", "Welcome to Python\n", "File Handling\n"]
file = open("example.txt", "w")
file.writelines(lines)
file.close()
➕ Appending to File
file = open("example.txt", "a")
file.write("\nThis is an additional line.")
file.close()
✅ Best Practice: Using with
Statement
with open("example.txt", "r") as file:
content = file.read()
print(content) # Automatically closes file
🔍 Check if File Exists
import os
if os.path.exists("example.txt"):
print("File exists!")
else:
print("File not found!")
❌ Delete a File
import os
if os.path.exists("example.txt"):
os.remove("example.txt")
print("File deleted.")
else:
print("File does not exist.")
🖼️ Binary File Handling
# Read binary file
with open("image.jpg", "rb") as file:
data = file.read()
print(data)
# Write binary file
with open("new_image.jpg", "wb") as file:
file.write(data)
🧾 Summary Table
Operation | Description | Example |
---|---|---|
Open file | open a file | open("file.txt", "r") |
Read file | read full content | file.read() |
Read line | read one line | file.readline() |
Read all lines | lines in list | file.readlines() |
Write file | overwrite content | file.write("Hello") |
Append | add content to end | file.write("\nMore text") |
Check file | before open/delete | os.path.exists("file.txt") |
Delete file | remove it | os.remove("file.txt") |
Now lets move to new concept for python programming for data science is Json module.
🧠 Understanding the JSON Module in Python
📌 What is JSON?
JSON (JavaScript Object Notation) is a lightweight, human-readable format to store and exchange data. It’s commonly used in APIs, web applications, and configuration files.
In Python, we work with JSON using the built-in json
module.
import json
🔄 1. Convert Python to JSON (Serialization)
✅ json.dumps(obj)
Converts a Python object (like a dictionary) into a JSON-formatted string.
import json
data = {"name": "Alice", "age": 25, "city": "New York"}
json_string = json.dumps(data)
print(json_string) # {"name": "Alice", "age": 25, "city": "New York"}
print(type(json_string)) # <class 'str'>
✅ json.dump(obj, file)
Writes JSON data directly to a file.
with open("data.json", "w") as file:
json.dump(data, file)
🔁 2. Convert JSON to Python (Deserialization)
✅ json.loads(json_string)
Converts a JSON-formatted string back into a Python object (like a dictionary).
json_data = '{"name": "Alice", "age": 25, "city": "New York"}'
python_obj = json.loads(json_data)
print(python_obj) # {'name': 'Alice', 'age': 25, 'city': 'New York'}
print(type(python_obj)) # <class 'dict'>
✅ json.load(file)
Reads JSON data from a file and converts it to a Python object.
with open("data.json", "r") as file:
python_data = json.load(file)
print(python_data)
🎨 3. Formatting JSON Output (Pretty Print)
Use indent
to make JSON more readable.
formatted_json = json.dumps(data, indent=4)
print(formatted_json)
Output:
{
"name": "Alice",
"age": 25,
"city": "New York"
}
📋 Summary Table of JSON Methods
Method | Description | Example |
---|---|---|
json.dumps(obj) | Convert Python object to JSON string | json.dumps(data) |
json.dump(obj, file) | Write JSON to file | json.dump(data, file) |
json.loads(json_string) | Convert JSON string to Python object | json.loads(json_data) |
json.load(file) | Read JSON from file | json.load(file) |
📝 Student Notes
Topic: Working with JSON in Python – Simple & Powerful
Key Takeaways:
- JSON is widely used in data science, APIs, and web development.
- Use
json.dumps()
andjson.loads()
for strings. - Use
json.dump()
andjson.load()
for files. - Always
import json
before working. - Use
indent
to format JSON for better readability.
Real-World Example:
When you call an API (like weather data or stock price), it often gives you results in JSON format. You can easily convert it into Python dictionaries using json.loads()
.
✅ What You Learned: Object Oriented Programming in Python
OOP (Object-Oriented Programming) is a way to organize and write Python code using real-world objects. It makes code reusable, clean, and easier to manage in large projects.
🔑 Key Concepts in OOP (Explained Simply)
Concept | Simple Meaning | Example |
---|---|---|
Class | Blueprint to build objects | class Car: |
Object | Actual thing created from class | car1 = Car() |
Attributes | Variables inside the object | self.name |
Methods | Functions inside the class | def drive(self): |
Encapsulation | Hides internal data | self.__balance |
Inheritance | One class inherits another | class Dog(Animal) |
Polymorphism | Same method, different result | fly() in Bird & Penguin |
Abstraction | Hides complex logic from user | @abstractmethod |
Magic Methods | Special methods like __str__ , __len__ | len(obj) |
Class vs Static Methods | Class methods use cls , static methods use nothing | @classmethod , @staticmethod |
🔧 Step-by-Step OOP Examples
- Creating a Class & Object
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def display_info(self):
return f"{self.brand} {self.model}"
car1 = Car("Toyota", "Camry")
print(car1.display_info()) # Toyota Camry
- Encapsulation (Hiding Data)
class BankAccount:
def __init__(self, balance):
self.__balance = balance
def get_balance(self):
return self.__balance
def deposit(self, amount):
if amount > 0:
self.__balance += amount
account = BankAccount(1000)
account.deposit(500)
print(account.get_balance()) # 1500
- Inheritance
class Animal:
def speak(self):
return "Animal makes sound"
class Dog(Animal):
def speak(self):
return "Bark"
dog = Dog()
print(dog.speak()) # Bark
- Multiple Inheritance
class A:
def method_a(self):
return "Method A"
class B:
def method_b(self):
return "Method B"
class C(A, B):
pass
obj = C()
print(obj.method_a()) # Method A
print(obj.method_b()) # Method B
- Polymorphism
class Bird:
def fly(self):
return "Birds can fly"
class Penguin(Bird):
def fly(self):
return "Penguins cannot fly"
penguin = Penguin()
print(penguin.fly()) # Penguins cannot fly
- Abstraction
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side * self.side
square = Square(4)
print(square.area()) # 16
- Magic Methods
class Book:
def __init__(self, title, pages):
self.title = title
self.pages = pages
def __str__(self):
return f"Book: {self.title}"
def __len__(self):
return self.pages
book = Book("Python Basics", 300)
print(str(book)) # Book: Python Basics
print(len(book)) # 300
- Class vs Static Methods
class Example:
class_var = "I am a class variable"
def instance_method(self):
return "Instance Method"
@classmethod
def class_method(cls):
return cls.class_var
@staticmethod
def static_method():
return "Static Method"
obj = Example()
print(obj.instance_method()) # Instance Method
print(Example.class_method()) # I am a class variable
print(Example.static_method()) # Static Method
✍️ Student Notes
Object Oriented Programming (OOP) in Python – A Beginner’s Guide
Object-Oriented Programming (OOP) is a style of coding that helps organize code into reusable objects. It’s like building LEGO blocks – each block is reusable and represents something meaningful.
OOP consists of classes and objects, where a class is the blueprint and an object is the actual usable item.
You’ll learn about Encapsulation (hiding data), Inheritance (reusing code), Polymorphism (same method, different behavior), and Abstraction (hiding complexity).
You also get introduced to:
- Magic methods like
__str__
and__len__
- Differences between
instance
,class
, andstatic
methods.
OOP is very important when building big applications or working with frameworks like Django in data science.
✅ Understanding List Comprehensions in Python (For Beginners)
List comprehensions in Python provide a short, elegant way to create lists. Instead of using long for
loops, Python allows you to generate new lists in a single line.
🧠 Think of It Like This:
Imagine you want to create a box of 5 chocolates 🍫.
- Normal way (using loop): You take 5 steps and add a chocolate one by one.
- List comprehension: You just say “Give me 5 chocolates in a box” — and boom 💥, it’s done in one line!
🧪 Syntax:
new_list = [expression for item in iterable if condition]
Example:
squares = [x*x for x in range(5)]
print(squares)
# Output: [0, 1, 4, 9, 16]
✏️ Let’s Break It Down:
[x*x for x in range(5)]
x*x
→ what you want to store in the list (square of x)for x in range(5)
→ loop through 0 to 4- No
if
condition here, but we can add one 👇
🎯 With a Condition:
even_squares = [x*x for x in range(10) if x % 2 == 0]
print(even_squares)
# Output: [0, 4, 16, 36, 64]
Only stores squares of even numbers.
🔁 Equivalent with Loop:
result = []
for x in range(10):
if x % 2 == 0:
result.append(x*x)
As you see, list comprehension is just a shorter version of this.
📝 Notes for Students:
- What is List Comprehension?
A one-liner technique to build lists from existing data using a loop and optional condition. - Why Use It?
- Saves time ⏳
- Cleaner code 📦
- Easier to read ✅
- When to Use?
Use it when you’re doing:- Simple operations in a loop
- Filtering data
- Transforming data values
📌 Quick Examples:
Task | List Comprehension |
---|---|
Create list of numbers 0–9 | [x for x in range(10)] |
Get even numbers from 0–9 | [x for x in range(10) if x % 2 == 0] |
Convert words to uppercase | [word.upper() for word in ["apple", "banana"]] |
🧠 Python Lambda Functions — Explained for Beginners
In this lesson, you’ll learn one of Python’s most powerful shortcuts — lambda functions.
🔍 What is a Lambda Function?
A lambda function is a mini function that:
- Has no name (also called anonymous function)
- Performs a single task
- Is written in one line
Think of it as a quick calculator for small tasks — no need to create full functions with def
. Python Programming For Data Science
🧱 Syntax:
lambda arguments: expression
lambda
: keyword to start the functionarguments
: input valuesexpression
: what you want to do (must be one line)
✅ Example:
square = lambda x: x ** 2
print(square(5)) # Output: 25
🔁 Using Lambda with map()
, filter()
, reduce()
1️⃣ map()
– Apply to each element
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, numbers))
print(squared) # [1, 4, 9, 16]
2️⃣ filter()
– Keep elements that match a condition
numbers = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # [2, 4, 6]
3️⃣ reduce()
– Collapse list to one result
from functools import reduce
numbers = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, numbers)
print(product) # 24
➕ Lambda with Multiple Arguments
add = lambda x, y: x + y
print(add(3, 7)) # Output: 10
maximum = lambda x, y: x if x > y else y
print(maximum(10, 5)) # Output: 10
🔃 Lambda in Sorting
Sort list of tuples by score:
students = [("Alice", 85), ("Bob", 78), ("Charlie", 92)]
students.sort(key=lambda student: student[1])
print(students)
# Output: [('Bob', 78), ('Alice', 85), ('Charlie', 92)]
💡 When to Use Lambda for Python Programming For Data Science?
✅ Use when:
- You need a short one-line function
- You’re using
map()
,filter()
, orreduce()
- You want to avoid full
def
function
❌ Avoid when:
- The function is long or needs many lines
- You want to reuse it with complex logic
✍️ Summary Table for Students:
Feature | Example |
---|---|
Basic Lambda | lambda x: x**2 |
With map() | map(lambda x: x**2, numbers) |
With filter() | filter(lambda x: x%2==0, numbers) |
With reduce() | reduce(lambda x, y: x*y, numbers) |
Multiple Arguments | lambda x, y: x + y |
Sorting with Lambda | sort(key=lambda x: x[1]) |
Oky so Python Programming For Data Science is very amazing. Just make sure Python Programming For Data Science is important.
Hope you like our guide on Python Programming For Data Science.