Use the following Noavari AI custom guide to quickly revise or align fundamental concepts and apply as needed to your custom project goals or objectives.
Python Fundamentals
Interactive Training System • Documented Curriculum Framework
01 Engine Foundations
Syntax layouts, environment installations, and foundational runtime execution mechanics.
02 Native Variables
Data modeling configurations, string manipulation pipelines, and core system types.
03 Operations & Control
Logical operations, truth conditions, pattern routing, and nested flow blocks.
04 Iteration Paradigms
Complex sequence processing loops, performance tuning, and collection generation.
05 Functional Design
Arguments routing, functional scope tracking, closures, and explicit lambda executions.
06 Complex Structures
Memory arrays, sequence access tracking, modification safety, and metadata sets.
07 Persistence Storage
Disk read/write contexts, file buffer safe handling, and standardized serialization.
08 Object Architecture
Custom class builds, structural inheritance models, and safe interface configurations.
09 Numerical Engineering
Fast vector matrix mathematics, shape transformations, and structural compute layers.
10 Data Structuring
Advanced dataframe analysis platforms, execution mapping, and layout processing pipelines.
1. Python Basics
Python is a high-level, interpreted, general-purpose programming language created by Guido van Rossum and first released in 1991. It emphasizes code readability and simplicity, making it an ideal first language for beginners and a powerful tool for experts.
1.1 Why Python?
- Simple, readable syntax resembling English
- Interpreted language — no compilation step needed
- Dynamically typed — no need to declare variable types
- Extensive standard library and vibrant ecosystem
- Cross-platform: runs on Windows, macOS, Linux
- Widely used in web development, data science, AI, automation, and more
1.2 Installing Python
Download Python from python.org/downloads. Always download the latest stable version. During installation on Windows, check ‘Add Python to PATH’.
1.3 Your First Python Program
# This is a comment in Python
print("Hello, World!")
# Output: Hello, World!
1.4 Python Indentation
Python uses 4 spaces (or 1 tab) per indentation level. Mixing spaces and tabs causes errors.
if True:
print("This is indented correctly") # 4 spaces
print("Same block")
print("Back to top level")
1.5 Comments
# Single-line comment
\"\"\"
This is a multi-line comment
or docstring used for documentation
\"\"\"
2. Variables & Data Types
Variables are containers for storing data. In Python, you don’t need to declare types explicitly — Python infers them automatically.
2.1 Variable Declaration
# Variable assignment
name = "Alice"
age = 25
height = 5.7
is_student = True
# Multiple assignment
x, y, z = 10, 20, 30
# Same value to multiple variables
a = b = c = 0
2.2 Core Data Types
| Data Type | Example | Description |
|---|---|---|
| int | x = 42 | Whole numbers (positive or negative) |
| float | pi = 3.14 | Decimal/floating-point numbers |
| str | name = "Alice" | Text / string of characters |
| bool | flag = True | Boolean: True or False |
| NoneType | val = None | Represents absence of a value |
| complex | z = 3 + 4j | Complex numbers |
2.3 Type Conversion
# Implicit (automatic) conversion
result = 5 + 2.0 # int + float = float (7.0)
# Explicit (manual) conversion
x = int("42") # str -> int
y = float(10) # int -> float
z = str(3.14) # float -> str
b = bool(0) # int -> bool (False)
# Check type
print(type(x)) # <class 'int'>
2.4 Strings in Detail
# String creation
single = 'Hello'
double = "World"
multi = \"\"\"Multi
line\"\"\"
# String methods
text = " Python Programming "
print(text.strip()) # "Python Programming"
print(text.lower()) # " python programming "
print(text.upper()) # " PYTHON PROGRAMMING "
print(text.replace("Python", "Java")) # " Java Programming "
print(text.split()) # ['Python', 'Programming']
# f-strings (modern string formatting)
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
# String slicing
s = "Python"
print(s[0]) # P
print(s[-1]) # n
print(s[0:3]) # Pyt
print(s[::-1]) # nohtyP (reversed)
3. Operators
Operators are symbols that perform operations on values or variables.
3.1 Arithmetic Operators
| Operator | Name | Example | Result |
|---|---|---|---|
| + | Addition | 5 + 3 | 8 |
| – | Subtraction | 10 – 4 | 6 |
| * | Multiplication | 3 * 4 | 12 |
| / | Division | 10 / 3 | 3.333… |
| // | Floor Division | 10 // 3 | 3 |
| % | Modulus | 10 % 3 | 1 |
| ** | Exponentiation | 2 ** 8 | 256 |
3.2 Comparison Operators
x, y = 10, 20
print(x == y) # False (equal)
print(x != y) # True (not equal)
print(x > y) # False (greater than)
print(x < y) # True (less than)
print(x >= 10) # True (greater than or equal)
print(x <= 5) # False (less than or equal)
3.3 Logical Operators
a, b = True, False
print(a and b) # False — both must be True
print(a or b) # True — at least one True
print(not a) # False — negation
# Practical example
age = 20
has_id = True
can_enter = age >= 18 and has_id
print(can_enter) # True
3.4 Assignment Operators
| Operator | Equivalent | Example |
|---|---|---|
| += | x = x + n | x += 5 |
| -= | x = x – n | x -= 3 |
| *= | x = x * n | x *= 2 |
| /= | x = x / n | x /= 4 |
| //= | x = x // n | x //= 2 |
| %= | x = x % n | x %= 3 |
| **= | x = x ** n | x **= 2 |
4. Conditional Statements
Conditional statements allow your program to make decisions based on conditions.
4.1 if / elif / else
score = 78
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print(f"Your grade is: {grade}") # Your grade is: C
4.2 Nested Conditionals
age = 22
has_license = True
if age >= 18:
if has_license:
print("You can drive!")
else:
print("You need a license.")
else:
print("You are too young to drive.")
4.3 Ternary (One-Line) Conditional
# Syntax: value_if_true if condition else value_if_false
x = 15
result = "Even" if x % 2 == 0 else "Odd"
print(result) # Odd
4.4 match-case Statement (Python 3.10+)
Python 3.10 introduced match-case (structural pattern matching), which is similar to switch-case in other languages but more powerful.
day = "Monday"
match day:
case "Monday" | "Tuesday" | "Wednesday" | "Thursday" | "Friday":
print("Weekday")
case "Saturday" | "Sunday":
print("Weekend")
case _:
print("Unknown day")
5. Loops
Loops allow you to repeat a block of code multiple times.
5.1 for Loop
# Iterating over a range
for i in range(5):
print(i) # 0, 1, 2, 3, 4
# range(start, stop, step)
for i in range(1, 10, 2):
print(i) # 1, 3, 5, 7, 9
# Iterating over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Iterating with index
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
5.2 while Loop
count = 0
while count < 5:
print(f"Count: {count}")
count += 1
# Infinite loop with break
while True:
user_input = input("Type quit to exit: ")
if user_input.lower() == "quit":
break
print(f"You entered: {user_input}")
5.3 Loop Control Statements
# break — exits the loop entirely
for i in range(10):
if i == 5:
break
print(i) # 0, 1, 2, 3, 4
# continue — skips the current iteration
for i in range(10):
if i % 2 == 0:
continue
print(i) # 1, 3, 5, 7, 9
# pass — placeholder, does nothing
for i in range(5):
pass # Placeholder for future code
5.4 List Comprehension
# Traditional approach
squares = []
for x in range(10):
squares.append(x ** 2)
# List comprehension (Pythonic way)
squares = [x ** 2 for x in range(10)]
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# With condition
evens = [x for x in range(20) if x % 2 == 0]
print(evens) # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
6. Functions
Functions are reusable blocks of code that perform a specific task. They help in organizing code, reducing repetition, and improving readability.
6.1 Defining and Calling Functions
def greet(name):
\"\"\"Return a greeting message.\"\"\"
return f"Hello, {name}!"
message = greet("Alice")
print(message) # Hello, Alice!
6.2 Parameters & Arguments
# Default parameters
def power(base, exponent=2):
return base ** exponent
print(power(3)) # 9 (uses default exponent=2)
print(power(2, 10)) # 1024
# Keyword arguments
print(power(exponent=3, base=5)) # 125
# *args — variable number of positional arguments
def add_all(*args):
return sum(args)
print(add_all(1, 2, 3, 4, 5)) # 15
# **kwargs — variable keyword arguments
def display_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
display_info(name="Alice", age=25, city="Delhi")
6.3 Lambda Functions
# Lambda: anonymous single-expression function
square = lambda x: x ** 2
print(square(7)) # 49
# Lambda with sorted()
students = [("Alice", 85), ("Bob", 72), ("Carol", 91)]
students.sort(key=lambda s: s[1], reverse=True)
print(students) # [('Carol', 91), ('Alice', 85), ('Bob', 72)]
6.4 Scope: Local vs Global
total = 0 # Global variable
def add(n):
global total # Access the global variable
total += n
add(5)
add(10)
print(total) # 15
7. Data Structures
Python provides four powerful built-in data structures: List, Tuple, Set, and Dictionary.
7.1 Lists
Lists are ordered, mutable (changeable) collections that allow duplicate values.
fruits = ["apple", "banana", "cherry"]
# Access
print(fruits[0]) # apple
print(fruits[-1]) # cherry
# Modify
fruits[1] = "blueberry"
# Methods
fruits.append("date") # Add to end
fruits.insert(1, "avocado") # Insert at index
fruits.remove("apple") # Remove by value
popped = fruits.pop() # Remove and return last
fruits.sort() # Sort in place
fruits.reverse() # Reverse in place
print(len(fruits)) # Length
7.2 Tuples
Tuples are ordered, immutable collections. Once created, they cannot be changed.
coordinates = (10.5, 20.3)
rgb = (255, 128, 0)
# Access (same as list)
print(coordinates[0]) # 10.5
# Unpacking
x, y = coordinates
print(x, y) # 10.5 20.3
# Tuples can be used as dict keys (lists cannot)
locations = {(0, 0): "origin", (1, 0): "right"}
7.3 Sets
Sets are unordered collections of unique elements. Great for removing duplicates and mathematical operations.
colors = {"red", "green", "blue", "red"}
print(colors) # {"red", "green", "blue"} — duplicate removed
# Set operations
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a | b) # Union: {1,2,3,4,5,6}
print(a & b) # Intersection: {3,4}
print(a - b) # Difference: {1,2}
print(a ^ b) # Symmetric: {1,2,5,6}
7.4 Dictionaries
Dictionaries store key-value pairs. Keys must be unique and immutable.
student = {
"name": "Alice",
"age": 20,
"grade": "A",
}
# Access
print(student["name"]) # Alice
print(student.get("score", 0)) # 0 (default if key missing)
# Modify
student["age"] = 21
student["city"] = "Mumbai"
# Iteration
for key, value in student.items():
print(f"{key}: {value}")
# Dictionary comprehension
squares = {x: x**2 for x in range(6)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
8. File Handling
Python makes it easy to read from and write to files using the built-in open() function.
8.1 Opening & Closing Files
| Mode | Description |
|---|---|
| r | Read (default) — file must exist |
| w | Write — creates new or overwrites existing |
| a | Append — adds to end of file |
| r+ | Read and write |
| rb / wb | Binary read / write |
with statement for file operations. It automatically closes the file even if an error occurs.
8.2 Writing to a File
# Using "with" statement (recommended — auto-closes file)
with open("example.txt", "w") as file:
file.write("Hello, World!\n")
file.write("Python File Handling\n")
# Writing multiple lines
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("example.txt", "w") as file:
file.writelines(lines)
8.3 Reading from a File
# Read entire file
with open("example.txt", "r") as file:
content = file.read()
print(content)
# Read line by line
with open("example.txt", "r") as file:
for line in file:
print(line.strip())
# Read all lines as a list
with open("example.txt", "r") as file:
lines = file.readlines()
8.4 Working with JSON Files
import json
# Write JSON
data = {"name": "Alice", "age": 25, "skills": ["Python", "ML"]}
with open("data.json", "w") as f:
json.dump(data, f, indent=4)
# Read JSON
with open("data.json", "r") as f:
loaded = json.load(f)
print(loaded["name"]) # Alice
9. Object-Oriented Programming (OOP)
OOP is a programming paradigm that organizes code around objects — instances of classes that bundle data (attributes) and behavior (methods).
9.1 Classes and Objects
class Dog:
# Class attribute (shared by all instances)
species = "Canis familiaris"
# Constructor method
def __init__(self, name, breed, age):
self.name = name # Instance attribute
self.breed = breed
self.age = age
# Instance method
def bark(self):
return f"{self.name} says: Woof!"
def description(self):
return f"{self.name} is a {self.age}-year-old {self.breed}."
# String representation
def __str__(self):
return self.description()
# Create objects (instances)
dog1 = Dog("Buddy", "Labrador", 3)
dog2 = Dog("Max", "Poodle", 5)
print(dog1.bark()) # Buddy says: Woof!
print(dog2.description()) # Max is a 5-year-old Poodle.
9.2 Inheritance
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError("Subclass must implement this")
class Cat(Animal): # Cat inherits from Animal
def speak(self):
return f"{self.name} says: Meow!"
class Dog(Animal):
def speak(self):
return f"{self.name} says: Woof!"
animals = [Cat("Whiskers"), Dog("Rex"), Cat("Luna")]
for animal in animals:
print(animal.speak())
9.3 Encapsulation & Properties
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private attribute (double underscore)
@property
def balance(self): # Getter
return self.__balance
@balance.setter
def balance(self, amount): # Setter with validation
if amount >= 0:
self.__balance = amount
else:
raise ValueError("Balance cannot be negative")
acc = BankAccount(1000)
print(acc.balance) # 1000
acc.balance = 1500
print(acc.balance) # 1500
10. Exception Handling
Exception handling allows programs to gracefully deal with errors at runtime without crashing.
10.1 try / except / else / finally
try:
numerator = int(input("Enter numerator: "))
denominator = int(input("Enter denominator: "))
result = numerator / denominator
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
except ValueError:
print("Error: Please enter valid integers!")
else:
# Runs only if no exception occurred
print(f"Result: {result}")
finally:
# Always runs (cleanup code)
print("Execution complete.")
10.2 Common Built-in Exceptions
| Exception | Description | Trigger Example |
|---|---|---|
| ValueError | Wrong type or value | int("abc") |
| TypeError | Operation on wrong type | "text" + 5 |
| ZeroDivisionError | Division by zero | 10 / 0 |
| IndexError | Index out of range | lst[99] |
| KeyError | Key not in dict | dict["missing"] |
| FileNotFoundError | File does not exist | open("x.txt") |
| AttributeError | Object has no attribute | str.nonexistent |
| ImportError | Module not found | import xyz |
10.3 Custom Exceptions
class InsufficientFundsError(Exception):
\"\"\"Custom exception for bank operations.\"\"\"
def __init__(self, amount, balance):
self.amount = amount
self.balance = balance
super().__init__(f"Cannot withdraw {amount}. Balance is {balance}.")
def withdraw(balance, amount):
if amount > balance:
raise InsufficientFundsError(amount, balance)
return balance - amount
try:
new_balance = withdraw(100, 200)
except InsufficientFundsError as e:
print(f"Error: {e}")
11. Introduction to NumPy
NumPy (Numerical Python) is the foundational library for scientific computing in Python. It provides a powerful N-dimensional array object and mathematical functions.
11.1 Installing & Importing NumPy
# Install via pip
# pip install numpy
import numpy as np
11.2 Creating Arrays
import numpy as np
# From a Python list
a = np.array([1, 2, 3, 4, 5])
print(a) # [1 2 3 4 5]
print(a.dtype) # int64
# 2D Array (Matrix)
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(matrix.shape) # (3, 3)
# Special arrays
print(np.zeros((3, 4))) # 3x4 matrix of zeros
print(np.ones((2, 3))) # 2x3 matrix of ones
print(np.eye(3)) # 3x3 identity matrix
print(np.arange(0, 10, 2)) # [0 2 4 6 8]
print(np.linspace(0, 1, 5)) # [0. 0.25 0.5 0.75 1.]
print(np.random.rand(3, 3)) # 3x3 random floats [0,1)
11.3 Array Operations
a = np.array([1, 2, 3, 4])
b = np.array([10, 20, 30, 40])
# Element-wise operations
print(a + b) # [11 22 33 44]
print(a * b) # [10 40 90 160]
print(a ** 2) # [1 4 9 16]
print(b / 10) # [1. 2. 3. 4.]
# Broadcasting
matrix = np.array([[1, 2, 3], [4, 5, 6]])
print(matrix + 10) # Adds 10 to every element
# Dot product / Matrix multiplication
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
print(np.dot(A, B))
# [[19 22]
# [43 50]]
11.4 Useful NumPy Functions
data = np.array([4, 7, 2, 9, 1, 5, 8, 3, 6])
print(np.min(data)) # 1
print(np.max(data)) # 9
print(np.mean(data)) # 5.0
print(np.median(data)) # 5.0
print(np.std(data)) # Standard deviation
print(np.sum(data)) # 45
print(np.sort(data)) # [1 2 3 4 5 6 7 8 9]
print(np.argmax(data)) # Index of max value: 3
# Reshaping
arr = np.arange(12)
reshaped = arr.reshape(3, 4)
print(reshaped)
# [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]
12. Introduction to Pandas
Pandas is a powerful data analysis library built on top of NumPy. It provides two primary data structures — Series and DataFrame — for working with structured data like spreadsheets or databases.
12.1 Installing & Importing Pandas
# Install via pip
# pip install pandas
import pandas as pd
import numpy as np
12.2 Series
# A 1D labeled array
scores = pd.Series([85, 92, 78, 90, 88],
index=["Alice", "Bob", "Carol", "Dave", "Eve"])
print(scores)
# Alice 85
# Bob 92
print(scores["Alice"]) # 85
print(scores.mean()) # 86.6
print(scores[scores > 88]) # Filter: Bob 92, Dave 90
12.3 DataFrame
# A 2D labeled table
data = {
"Name": ["Alice", "Bob", "Carol", "Dave"],
"Age": [24, 30, 22, 35],
"Dept": ["IT", "HR", "IT", "Finance"],
"Salary": [60000, 55000, 62000, 70000]
}
df = pd.DataFrame(data)
print(df)
# Basic inspection
print(df.shape) # (4, 4)
print(df.dtypes) # Data types per column
print(df.describe()) # Statistical summary
print(df.head(3)) # First 3 rows
print(df.tail(2)) # Last 2 rows
12.4 Data Selection & Filtering
# Select column
print(df["Name"])
print(df[["Name", "Salary"]]) # Multiple columns
# Select rows by index
print(df.iloc[0]) # First row (integer location)
print(df.loc[2]) # Row with label/index 2
# Filtering rows
it_staff = df[df["Dept"] == "IT"]
high_earners = df[df["Salary"] > 60000]
combined = df[(df["Dept"] == "IT") & (df["Age"] < 30)]
12.5 Data Manipulation
# Add new column
df["Tax"] = df["Salary"] * 0.1
# Apply function
df["Name_Upper"] = df["Name"].apply(str.upper)
# Group by
dept_avg = df.groupby("Dept")["Salary"].mean()
print(dept_avg)
# Sort
df_sorted = df.sort_values("Salary", ascending=False)
# Drop column
df.drop(columns=["Tax"], inplace=True)
# Handle missing values
df.dropna() # Remove rows with NaN
df.fillna(0) # Fill NaN with 0
df.isnull().sum() # Count missing per column
12.6 Reading & Writing Data
# CSV
df = pd.read_csv("data.csv")
df.to_csv("output.csv", index=False)
# Excel
df = pd.read_excel("data.xlsx", sheet_name="Sheet1")
df.to_excel("output.xlsx", index=False)
# JSON
df = pd.read_json("data.json")
df.to_json("output.json", orient="records")
Quick Reference Summary
| Topic | Key Architectural Concepts |
|---|---|
| Python Basics | Indentation, comments, print(), interpreted syntax structure execution. |
| Variables & Types | Dynamic allocation initialization, type casting, sequence transformations. |
| Operators | Evaluation metrics, comparison checks, assignment variables configurations. |
| Conditionals | Pattern routing blocks, logic branch paths, pattern verification matrices. |
| Loops | Sequential extraction parameters, block bypass routing metrics, comprehension structures. |
| Functions | Parameters declaration parsing, dynamic scope checking, inline expressions management. |
| Data Structures | Mutability processing criteria, unique sorting algorithms, key mapping indexing parameters. |
| File Handling | Streaming safe tracking, storage serialization, data structural access schemas. |
| OOP Layers | Entity classification modeling templates, abstract class overrides, attribute isolation blocks. |
| Exception Logic | Runtime interception pipelines, error classification tracking matrices, cleanup routines. |
| NumPy Compute | Vector structural indexing blocks, matrix transformation algorithms, alignment pipelines. |
| Pandas Platforms | Dataframe transformation environments, grouping aggregation models, transactional input/output. |