SECTION 1 – Python Foundations
1.1 Basics & Syntax
📚 What: The rules for writing Python code.
🧠 AI/ML Relevance: Every AI/ML model in Python — whether it’s Scikit-learn, TensorFlow, or PyTorch — uses this basic syntax.
💻 Example:
# Single-line comment
print("Hello AI") # Output: Hello AI
"""
Multi-line comment:
This program prints Hello AI
"""
🏋 Exercise: Print "Welcome to AI Learning"
on the screen.
1.2 Comments & Indentation
📚 What: Comments help document your code; indentation defines code blocks.
🧠 AI/ML Relevance:
Comments explain data cleaning steps.
Indentation ensures loops and functions run correctly.
💻 Example:
# Loop through training epochs
for epoch in range(3):
print(f"Epoch {epoch+1} started")
print("Training complete for this epoch")
🏋 Exercise: Write a loop that prints "Processing batch X"
for batches 1–5.
1.3 Variables & Naming
📚 What: Variables store data in memory.
🧠 AI/ML Relevance: Store dataset paths, hyperparameters, metrics.
💻 Example:
dataset_path = "data/iris.csv" # string
learning_rate = 0.001 # float
epochs = 50 # int
use_gpu = True # boolean
🏋 Exercise: Create variables for:
AI project name
Batch size
Dropout rate
1.4 Constants
📚 What: Fixed values you don’t change.
🧠 AI/ML Relevance: Useful for fixed paths, API keys, default configs.
💻 Example:
PI = 3.14159
DEFAULT_EPOCHS = 10
1.5 Data Types
📚 What: Different kinds of values Python can store.
Type | Example | AI/ML Usage |
---|---|---|
int | epochs = 10 | Number of iterations |
float | lr = 0.01 | Learning rate |
str | "Neural Network" | Model name |
bool | True | Flags |
list | [0.9, 0.92, 0.95] | Accuracy history |
tuple | (224, 224) | Image size |
dict | {"lr": 0.001, "epochs": 10} | Model configs |
set | {"cat", "dog"} | Unique labels |
💻 Example:
accuracy_scores = [0.88, 0.90, 0.92]
model_config = {"layers": 3, "activation": "relu"}
🏋 Exercise: Create:
List of 3 loss values
Dictionary with model name & accuracy
1.6 Type Conversion
📚 What: Changing a variable from one type to another.
🧠 AI/ML Relevance: Convert strings from CSV into numbers for model training.
💻 Example:
epochs = int("50") # string → int
lr = float("0.01") # string → float
model_id = str(123) # int → string
🏋 Exercise: Convert "32"
, "0.002"
, "True"
into int, float, and boolean.
1.7 Operators
📚 What: Symbols to perform operations.
Arithmetic:
accuracy = 90
total = 100
print("Accuracy %:", accuracy / total * 100)
Comparison:
if accuracy > 85:
print("Good model")
Logical:
if accuracy > 85 and total == 100:
print("Perfect data size")
🏋 Exercise: Check if accuracy > 0.85 and loss < 0.2.
1.8 Strings & Methods
📚 What: Strings hold text; methods manipulate them.
🧠 AI/ML Relevance: NLP preprocessing (lowercasing, tokenization).
💻 Example:
text = " Machine Learning is FUN! "
print(text.lower()) # lowercase
print(text.strip()) # remove spaces
print(text.replace("FUN", "Powerful")) # replace word
🏋 Exercise:
From " THIS product is Excellent!!! "
:
Lowercase it
Remove spaces
Remove
!!!
Replace
"product"
with"model"
Python 3.12, grouped logically so it’s easy to study.
1. Changing Case
Method | Description | Example |
---|---|---|
str.upper() | Converts all characters to uppercase. | "hello".upper() → "HELLO" |
str.lower() | Converts all characters to lowercase. | "Hello".lower() → "hello" |
str.title() | Capitalizes first letter of each word. | "hello world".title() → "Hello World" |
str.capitalize() | Capitalizes first letter, rest lowercase. | "hELLO".capitalize() → "Hello" |
str.casefold() | Lowercases more aggressively (for comparisons). | "ß".casefold() → "ss" |
str.swapcase() | Swaps uppercase to lowercase and vice versa. | "HeLLo".swapcase() → "hEllO" |
2. Alignment & Padding
Method | Description | Example |
---|---|---|
str.center(width, fillchar) | Centers the string. | "hi".center(6, "-") → "--hi--" |
str.ljust(width, fillchar) | Left-aligns with padding. | "hi".ljust(6, ".") → "hi...." |
str.rjust(width, fillchar) | Right-aligns with padding. | "hi".rjust(6, ".") → "....hi" |
str.zfill(width) | Pads with zeros on the left. | "42".zfill(5) → "00042" |
3. Searching & Finding
Method | Description | Example |
---|---|---|
str.find(sub) | Returns lowest index of sub or -1 . | "hello".find("l") → 2 |
str.rfind(sub) | Returns highest index of sub or -1 . | "hello".rfind("l") → 3 |
str.index(sub) | Like find() but raises ValueError if not found. | "hello".index("e") → 1 |
str.rindex(sub) | Like rfind() but raises error if not found. | "hello".rindex("l") → 3 |
str.count(sub) | Counts non-overlapping occurrences. | "banana".count("na") → 2 |
str.startswith(prefix) | Checks if string starts with prefix. | "python".startswith("py") → True |
str.endswith(suffix) | Checks if string ends with suffix. | "python".endswith("on") → True |
4. Checking String Content
(All return True
or False
.)
Method | Example |
---|---|
str.isalpha() → "Hello".isalpha() → True | |
str.isdigit() → "123".isdigit() → True | |
str.isalnum() → "Hello123".isalnum() → True | |
str.isdecimal() → "123".isdecimal() → True | |
str.isnumeric() → "²".isnumeric() → True | |
str.isspace() → " ".isspace() → True | |
str.islower() → "hello".islower() → True | |
str.isupper() → "HELLO".isupper() → True | |
str.istitle() → "Hello World".istitle() → True | |
str.isascii() → "A".isascii() → True |
5. Modifying & Replacing
Method | Description | Example |
---|---|---|
str.replace(old, new, count) | Replaces occurrences of old with new . | "banana".replace("na", "NA") → "baNANA" |
str.strip(chars) | Removes leading/trailing whitespace or given chars. | " hello ".strip() → "hello" |
str.lstrip(chars) | Removes leading chars. | "***hi".lstrip("*") → "hi" |
str.rstrip(chars) | Removes trailing chars. | "hi***".rstrip("*") → "hi" |
str.removeprefix(prefix) | Removes prefix if present. | "Python3".removeprefix("Python") → "3" |
str.removesuffix(suffix) | Removes suffix if present. | "file.txt".removesuffix(".txt") → "file" |
6. Splitting & Joining
Method | Description | Example |
---|---|---|
str.split(sep) | Splits into list by separator. | "a,b,c".split(",") → ['a', 'b', 'c'] |
str.rsplit(sep) | Splits from right side. | "a,b,c".rsplit(",", 1) → ['a,b', 'c'] |
str.splitlines() | Splits by line breaks. | "a\nb".splitlines() → ['a', 'b'] |
str.join(iterable) | Joins elements with string as separator. | ",".join(['a', 'b']) → "a,b" |
str.partition(sep) | Splits into 3 parts: before, sep, after. | "abc:def".partition(":") → ('abc', ':', 'def') |
str.rpartition(sep) | Like partition() but from right side. | "abc:def:ghi".rpartition(":") → ('abc:def', ':', 'ghi') |
7. Encoding
Method | Description | Example |
---|---|---|
str.encode(encoding) | Encodes string into bytes. | "hello".encode("utf-8") → b'hello' |
8. Formatting
Method | Description | Example |
---|---|---|
str.format() | Formats placeholders {} with values. | "Hello {}".format("John") → "Hello John" |
str.format_map(mapping) | Uses a dict for formatting. | "{name}".format_map({"name": "John"}) → "John" |
str.maketrans() | Creates mapping table for translation. | table = str.maketrans("abc", "123") |
str.translate(table) | Applies mapping table. | "abc".translate(table) → "123" |
9. Tabs & Whitespace
Method | Example |
---|---|
str.expandtabs(tabsize) → "a\tb".expandtabs(4) → "a b" |
✅ Tip for Learning:
To quickly see all methods in your Python, run:
print(dir(str))
and then use:
help(str.methodname)
to read details.
CALL +94 777 33 7279 | EMAIL ITCLASSSL@GMAIL.COM
YouTube https://www.youtube.com/channel/UCJojbxGV0sfU1QPWhRxx4-A
LinkedIn https://www.linkedin.com/in/ict-bit-tuition-class-software-development-colombo/
WordPress https://computerclassinsrilanka.wordpress.com
quora https://www.quora.com/profile/BIT-UCSC-UoM-Final-Year-Student-Project-Guide
Newsletter https://sites.google.com/view/the-leaning-tree/newsletter
Wix https://itclasssl.wixsite.com/icttraining
Web https://itclass-bit-ucsc-uom-php-final-project.business.site/
mystrikingly https://bit-ucsc-uom-final-year-project-ideas-help-guide-php-class.mystrikingly.com/
https://elakiri.com/threads/bit-ucsc-uom-php-mysql-project-guidance-and-individual-classes-in-colombo.1627048/