Friday, August 15, 2025

Python SECTION 2 – Control Flow Conditionals – if, elif, else Loops Comprehensions

SECTION 2 – Control Flow (Weeks 2–3)


2.1 Conditionals – if, elif, else

📚 What: Conditionals let your program make decisions.
🧠 AI/ML Relevance:

  • Check accuracy thresholds before deployment

  • Decide model tuning steps based on loss value

  • Perform different preprocessing for text vs image datasets

💻 Example: Accuracy Evaluation

accuracy = 0.88

if accuracy > 0.9:
    print("Excellent model")
elif accuracy > 0.8:
    print("Good model, but can improve")
else:
    print("Needs more training")

Nested Conditions

📚 What: Condition inside another condition.
🧠 AI/ML Relevance:

  • Check multiple model performance metrics

  • Apply rules for different dataset conditions

💻 Example: Accuracy + Loss Check

accuracy = 0.92
loss = 0.15

if accuracy > 0.9:
    if loss < 0.2:
        print("Ready for deployment")
    else:
        print("Accuracy is fine, but reduce loss")

🏋 Exercise:
Write a conditional that:

  1. Checks if accuracy > 0.85

  2. If true, checks if loss < 0.15 → print "Excellent"

  3. Else print "Needs work"


2.2 Loops


For Loops

📚 What: Repeat code for a fixed number of iterations or over a collection.
🧠 AI/ML Relevance:

  • Iterate over datasets

  • Process batches in training

  • Apply transformations to every data point

💻 Example: Processing Dataset Batches

batches = ["Batch 1", "Batch 2", "Batch 3"]

for batch in batches:
    print(f"Processing {batch}")

While Loops

📚 What: Repeat until a condition becomes false.
🧠 AI/ML Relevance:

  • Continue training until loss is below a threshold

  • Keep collecting data until dataset size is reached

💻 Example: Training Until Loss Threshold

loss = 1.0
while loss > 0.1:
    print(f"Training... current loss = {loss}")
    loss -= 0.2
print("Training stopped: Loss threshold met")

Break & Continue

📚 What:

  • break → Stop the loop early

  • continue → Skip the rest of the current iteration

💻 Example: Stop Training Early

losses = [0.5, 0.3, 0.15, 0.09]

for loss in losses:
    if loss < 0.1:
        print("Loss is low enough, stopping early")
        break
    print(f"Current loss: {loss}")

💻 Example: Skip Bad Data

data_points = [1, None, 3, None, 5]

for point in data_points:
    if point is None:
        continue
    print(f"Processing: {point}")

range()

📚 What: Generates a sequence of numbers for looping.

💻 Example: 5 Epochs Training

for epoch in range(1, 6):
    print(f"Training Epoch {epoch}")

Loop Over Iterables

📚 What: Loop directly over lists, dicts, sets, tuples.
💻 Example: Looping Over Dictionary of Model Parameters

params = {"learning_rate": 0.001, "batch_size": 32, "epochs": 10}

for key, value in params.items():
    print(f"{key}: {value}")

🏋 Exercise:
Loop over a dictionary containing "model", "accuracy", and "loss" and print them in key: value format.


2.3 Comprehensions

📚 What: Shorter, cleaner way to create lists, sets, dicts from loops.
🧠 AI/ML Relevance: Quickly transform datasets without writing long loops.


List Comprehension

💻 Example: Squaring All Loss Values

losses = [0.5, 0.3, 0.15]
squared_losses = [loss**2 for loss in losses]
print(squared_losses)

Tuple Comprehension (Actually Generators in Python)

💻 Example: Generate Accuracy Values on the Fly

accuracies = (round(acc, 2) for acc in [0.82, 0.91, 0.88])
for acc in accuracies:
    print(acc)

Dict Comprehension

💻 Example: Mapping Model Names to Accuracies

models = ["Model_A", "Model_B", "Model_C"]
accs = [0.85, 0.90, 0.88]

model_performance = {model: acc for model, acc in zip(models, accs)}
print(model_performance)

Set Comprehension

💻 Example: Unique Label Extraction

labels = ["cat", "dog", "cat", "bird", "dog"]
unique_labels = {label for label in labels}
print(unique_labels)

🏋 Final Exercise for Section 2:
Given:

models = ["A", "B", "C"]
accuracies = [0.9, 0.85, 0.92]
  1. Create a dictionary mapping each model to its accuracy (dict comprehension)

  2. Create a list of only the accuracies above 0.88 (list comprehension)

  3. Loop over the dictionary and print "Model X has accuracy Y"




Python dictionary methods in action.

# Create a dictionary for months
months = {
    "January": 31,
    "February": 28,
    "March": 31,
    "April": 30,
    "May": 31,
    "June": 30
}

print("Original dictionary:", months)

1. Access values

print("Days in February:", months["February"])
print("Days in May (get method):", months.get("May"))
print("Non-existing month with default:", months.get("December", "Not Found"))

2. Add or update

months["July"] = 31  # Add
months["February"] = 29  # Update (Leap year)
print("After add/update:", months)

3. Remove — pop()

removed_days = months.pop("June")
print("Removed June (days =", removed_days, "):", months)

4. Remove last item — popitem()

last_item = months.popitem()
print("Removed last item:", last_item)
print("After popitem:", months)

5. Delete — del

del months["April"]
print("After deleting April:", months)

6. Clear dictionary

temp_months = months.copy()
temp_months.clear()
print("After clear:", temp_months)

7. Copy dictionary

months_copy = months.copy()
print("Copied dictionary:", months_copy)

8. Keys, Values, Items

print("Keys:", months.keys())
print("Values:", months.values())
print("Items:", months.items())

9. Loop through dictionary

for month, days in months.items():
    print(f"{month}: {days} days")

10. Check membership

print("Is 'March' in months?", "March" in months)
print("Is 'December' not in months?", "December" not in months)

11. Update with another dictionary

months.update({"August": 31, "September": 30})
print("After update:", months)

12. Dictionary comprehension

month_lengths = {month: len(month) for month in months}
print("Month name lengths:", month_lengths)

Tuple example similar to the list and set ones.
Tuples are ordered, immutable collections — so you can’t change items after creation (no append(), remove(), etc.), but you can still use many useful built-in functions.


# Create a tuple of fruits
fruits = ("apple", "banana", "cherry", "date", "elderberry", "banana")

print("Original tuple:", fruits)

1. Access elements by index

print("First fruit:", fruits[0])
print("Last fruit:", fruits[-1])

2. Slicing

print("First 3 fruits:", fruits[:3])
print("Fruits from index 2 onwards:", fruits[2:])

3. Count — count()

print("Count of 'banana':", fruits.count("banana"))

Counts occurrences of a value.


4. Index — index()

print("Index of 'cherry':", fruits.index("cherry"))

Finds the first occurrence of a value.


5. Length — len()

print("Number of fruits:", len(fruits))

6. Membership test

print("Is 'apple' in tuple?", "apple" in fruits)
print("Is 'mango' not in tuple?", "mango" not in fruits)

7. Concatenation

more_fruits = ("fig", "grape")
combined = fruits + more_fruits
print("Combined tuple:", combined)

8. Repetition

repeat_fruits = ("apple", "banana") * 2
print("Repeated tuple:", repeat_fruits)

9. Min / Max / Sum (works only if all items are same type)

numbers = (5, 2, 9, 1)
print("Min number:", min(numbers))
print("Max number:", max(numbers))
print("Sum:", sum(numbers))

10. Tuple unpacking

a, b, c, *rest = fruits
print("a:", a)
print("b:", b)
print("c:", c)
print("rest:", rest)

11. Convert to list (to modify) and back

temp_list = list(fruits)
temp_list.append("honeydew")
fruits = tuple(temp_list)
print("Modified tuple:", fruits)

Python set functions/methods with examples.
Remember: a set is unordered, does not allow duplicates, and elements must be immutable.


# Create a set of fruits
fruits = {"apple", "banana", "cherry", "date", "elderberry"}

print("Original set:", fruits)

1. Add — add()

fruits.add("fig")
print("After add:", fruits)

Adds a single item.


2. Update — update()

fruits.update(["grape", "honeydew"])
print("After update:", fruits)

Adds multiple items.


3. Remove — remove()

fruits.remove("banana")
print("After remove:", fruits)

Removes an item; error if not found.


4. Discard — discard()

fruits.discard("kiwi")  # No error if not found
print("After discard (kiwi):", fruits)

Removes item without error.


5. Pop — pop()

removed = fruits.pop()
print("Popped item:", removed)
print("After pop:", fruits)

Removes a random item (since sets are unordered).


6. Clear — clear()

temp_set = fruits.copy()
temp_set.clear()
print("After clear:", temp_set)

Removes all items.


7. Copy — copy()

fruits_copy = fruits.copy()
print("Copied set:", fruits_copy)

Shallow copy.


8. Union — union() / |

set_a = {"apple", "banana", "mango"}
set_b = {"banana", "kiwi", "orange"}
print("Union:", set_a.union(set_b))
print("Union (|):", set_a | set_b)

Combines sets, removes duplicates.


9. Intersection — intersection() / &

print("Intersection:", set_a.intersection(set_b))
print("Intersection (&):", set_a & set_b)

Items common to both sets.


10. Difference — difference() / -

print("Difference:", set_a.difference(set_b))
print("Difference (-):", set_a - set_b)

Items in the first set but not the second.


11. Symmetric Difference — symmetric_difference() / ^

print("Symmetric Difference:", set_a.symmetric_difference(set_b))
print("Symmetric Difference (^):", set_a ^ set_b)

Items in either set but not both.


12. isdisjoint()

print("Is disjoint?:", {"pineapple"} .isdisjoint({"mango"}))

True if no elements in common.


13. issubset() / issuperset()

print("Is subset?:", {"apple", "banana"}.issubset(set_a))
print("Is superset?:", set_a.issuperset({"banana"}))

14. len()

print("Number of fruits:", len(fruits))

Counts items in the set.


 Python list function / method with examples so you have a ready reference.


# Create a list of fruits
fruits = ["apple", "banana", "cherry", "date", "elderberry"]

print("Original list:", fruits)

1. Append — append()

fruits.append("fig")
print("After append:", fruits)

Adds an item to the end.


2. Insert — insert()

fruits.insert(2, "blueberry")
print("After insert:", fruits)

Inserts at a specific index.


3. Extend — extend()

fruits.extend(["grape", "honeydew"])
print("After extend:", fruits)

Adds multiple items.


4. Remove — remove()

fruits.remove("banana")
print("After remove:", fruits)

Removes first occurrence of a value.


5. Pop — pop()

popped = fruits.pop(3)
print("Popped item:", popped)
print("After pop:", fruits)

Removes by index (last item if no index given).


6. Clear — clear()

temp_list = fruits.copy()
temp_list.clear()
print("After clear:", temp_list)

Removes all items.


7. Index — index()

print("Index of cherry:", fruits.index("cherry"))

Finds the first occurrence of a value.


8. Count — count()

print("Count of 'apple':", fruits.count("apple"))

Counts how many times a value appears.


9. Sort — sort()

fruits.sort()
print("Sorted list:", fruits)

fruits.sort(reverse=True)
print("Reverse sorted list:", fruits)

Sorts in place (alphabetically by default).


10. Reverse — reverse()

fruits.reverse()
print("After reverse:", fruits)

Reverses order.


11. Copy — copy()

new_fruits = fruits.copy()
print("Copied list:", new_fruits)

Shallow copy of the list.


12. Slicing

print("First 3 fruits:", fruits[:3])
print("Last 2 fruits:", fruits[-2:])

Access sublists.


13. List Comprehension

long_names = [f for f in fruits if len(f) > 5]
print("Fruits with names longer than 5 letters:", long_names)

Create lists with conditions.


14. Length — len()

print("Number of fruits:", len(fruits))

Gets number of items.


15. Min / Max

print("Min fruit (alphabetically):", min(fruits))
print("Max fruit (alphabetically):", max(fruits))

import sys

# Join all arguments into one string

full_text = " ".join(sys.argv[1:])

# Example: full_text = "Arguments passed is <123> from command"

# Extract the part between < and >

start = full_text.find("<") + 1

end = full_text.find(">")

number = full_text[start:end]

print(number)


### 💻✨ Master ICT from Beginner to Pro with an Expert! ✨💻


🔹 Individual & Group ICT Classes (Online) – Tailored for All Levels:


📘 For School Students:


 Grade 1 to Grade 6 – Fun & interactive ICT basics

 GCE O/L ICT – Full syllabus coverage + past paper practice

 GCE A/L ICT – Theory, practicals, and revision strategies


🎓 For University & Higher Studies:


 BIT | BSc in Computer Science | Diploma ICT Courses

 Programming, Web Design, Databases, AI, Networking & more


👨‍🏫 Why Join Us?


 Conducted by a qualified ICT Teacher & Software Engineer with 10+ years of experience

 Personalized guidance for individual or group learners

 Real-world project training and exam-focused preparation

 Friendly teaching style that makes learning engaging and effective


🌐 Learn from Anywhere – Anytime

Join our online classes and experience the difference!


📞 Call / WhatsApp Now to Reserve Your Spot!

💥 Whatsapp https://wa.link/b72px4

💥 YouTube https://www.youtube.com/channel/UCJojbxGV0sfU1QPWhRxx4-A

💥 Blog https://localedxcelcambridgeictcomputerclass.blogspot.com/

---


🔖 Tags:

#ICTClasses #OnlineICT #Grade1to6ICT #GCEOICT #GCEALICT #BIT #BScComputerScience #OnlineLearning #ICTTeacher #SoftwareEngineer #SriLankaEducation #CodingForKids #ProgrammingClasses #ICTTuition #LearnICTOnline






No comments:

Post a Comment