Lesson 2 – Loops and Arrays (With A.I YOLO Example)
The goal of this lesson is to run real AI code using YOLOv8 and see how an AI model detects objects in an image.
In this example, the YOLO model analyzes a picture stored on your computer in the folder C:\AI\PICS, detects objects such as people, cows, and balls, and prints how many of each it finds.
You can save your test images into C:\AI\PICS and replace the file name in the code (for example, pic1.png
) to analyze different images with artificial intelligence.
remark Jupiter notebook – run this code to know where you locate
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
# how to know Jupyter Notebook’ files are : import os import sys from pathlib import Path import jupyter_core print("Jupyter Notebook current program full path : ", os.getcwd(), " or " , Path().resolve()) print(jupyter_core.paths.SYSTEM_JUPYTER_PATH) print(sys.prefix) print(os.path.expanduser("~")) # open windows file explorer for the current Jupyter Notebook’ path=Path().resolve() os.startfile(path) |
we will use this code and learn how it works
1 2 3 4 5 6 7 |
count_cows = 0 for box in results[0].boxes: cls_id = int(box.cls[0]) label = model.names[cls_id] if label == "cow": count_cows += 1 print("Number of cows detected:", count_cows) |
Lesson 2 to teach loops and arrays using a real YOLO-style example
Before we use YOLO-style data, let’s understand dictionaries and arrays with simple
Lesson – Dictionaries and Loops in Python
A dictionary in Python stores data as key → value pairs.
1 2 3 4 5 6 7 8 9 |
# Learn Python to A.I Programming - Robotronix.co.il , Yaniv Maor # Example 1 – Simple dictionary robot = {"name": "CARTi", "type": "AI Robot", "version": 1.0} # Print each value by its key print(robot["name"]) print(robot["type"]) print(robot["version"]) |
Output:
CARTi
AI Robot
1.0
2. Adding and Changing Values in a Dictionary
1 2 3 4 5 6 7 8 9 |
robot = {"name": "CARTi", "type": "AI Robot", "version": 1.0} # Add a new key robot["battery"] = "95%" # Change an existing value robot["version"] = 2.0 print(robot) |
Output:
{'name': 'CARTi', 'type': 'AI Robot', 'version': 2.0, 'battery': '95%'}
3. Looping Through a Dictionary
1 2 3 4 |
robot = {"name": "CARTi", "type": "AI Robot", "version": 2.0} for key, value in robot.items(): print(key, "→", value) |
Output:
name → CARTi
type → AI Robot
version → 2.0
4. Looping Through a 1-D Array (List)
1 2 3 4 5 6 7 |
# Learn Python to A.I Programming - Robotronix.co.il , Yaniv Maor animals = ["cow", "dog", "cat", "horse", "bird"] # Loop through all animals for a in animals: print("Animal:", a) |
Output:
Animal: cow
Animal: dog
Animal: cat
Animal: horse
Animal: bird
1 2 3 4 5 |
# Learn Python to A.I Programming - Robotronix.co.il , Yaniv Maor # Example 1 – Basic for-loop over numbers # five will not print - print from 0 to 4 for i in range(5): print("Loop index:", i) |
Output:
Loop index: 0
Loop index: 1
Loop index: 2
Loop index: 3
Loop index: 4
5. Loop with Index (using range and len)
1 2 3 4 5 |
# Learn Python to A.I Programming - Robotronix.co.il , Yaniv Maor animals = ["cow", "dog", "cat"] for i in range(len(animals)): print("Index:", i, "| Animal:", animals[i]) |
Output:
Index: 0 | Animal: cow
Index: 1 | Animal: dog
Index: 2 | Animal: cat
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
# Learn Python to A.I Programming - Robotronix.co.il , Yaniv Maor # Example 6.6 – Nested list (2-D array) matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] # Outer loop: go through each row for row in matrix: print("Row:", row) # Print the full row first # Inner loop: print each number in the row for value in row: print(" Matrix value:", value) |
Output
Row: [1, 2, 3]
Matrix value: 1
Matrix value: 2
Matrix value: 3
Row: [4, 5, 6]
Matrix value: 4
Matrix value: 5
Matrix value: 6
Row: [7, 8, 9]
Matrix value: 7
Matrix value: 8
Matrix value: 9
Explanation
The outer loop prints each full row of the matrix.
The inner loop then prints each element inside that row, one by one.
This helps visualize the 2-D structure — a key concept in A.I. for handling image pixels or data grids
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 |
# Learn Python to A.I Programming - Robotronix.co.il , Yaniv Maor # Lesson 6 – Loops and YOLO-Style Detections # ----------------------------------------------- # Example 6.1 – Basic loop through a simple list animals = ["cow", "dog", "cat"] for a in animals: print("Animal:", a) print("-" * 40) # Example 6.2 – Loop and show the index of each element for i in range(len(animals)): print("Animal index:", i, "| Name:", animals[i]) print("-" * 40) # Example 6.3 – Add detection confidence values (like YOLO) confidences = [0.92, 0.85, 0.88] for i in range(len(animals)): print(f"Detected {animals[i]} with confidence {confidences[i]}") print("-" * 40) # Example 6.4 – Filter detections based on confidence for i in range(len(animals)): if confidences[i] > 0.9: print(f"High confidence detection: {animals[i]} ({confidences[i]})") print("-" * 40) # Example 6.5 – Represent YOLO results as list of dictionaries results = [ {"cls": "cow", "conf": 0.92}, {"cls": "dog", "conf": 0.85}, {"cls": "cat", "conf": 0.88} ] for box in results: print("Detected:", box["cls"], "| Confidence:", round(box["conf"], 2)) print("-" * 40) # Example 6.6 – Nested list (2-D array) matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] for row in matrix: for value in row: print("Matrix value:", value) print("-" * 40) # Example 6.7 – Simulate YOLO results for several frames results = [ {"boxes": [{"cls": "cow", "conf": 0.91}, {"cls": "dog", "conf": 0.87}]}, {"boxes": [{"cls": "car", "conf": 0.94}, {"cls": "person", "conf": 0.96}]} ] for frame in results: print("---- New Frame ----") for box in frame["boxes"]: print("Detected:", box["cls"], "| Confidence:", round(box["conf"], 2)) print("-" * 40) # Example 6.8 – Counting detections by class results = [ {"cls": "cow", "conf": 0.92}, {"cls": "dog", "conf": 0.85}, {"cls": "cow", "conf": 0.88}, {"cls": "cat", "conf": 0.90} ] count = {"cow": 0, "dog": 0, "cat": 0} for box in results: label = box["cls"] count[label] += 1 print("Detection count:", count) print("-" * 40) # Example 6.9 – Filter detections above threshold results = [ {"cls": "person", "conf": 0.95}, {"cls": "dog", "conf": 0.45}, {"cls": "car", "conf": 0.88} ] filtered = [] for box in results: if box["conf"] >= 0.8: filtered.append(box) print("Filtered results:", filtered) print("-" * 40) # Example 6.10 – Full YOLO-style detections with coordinates results = [ {"cls": "person", "conf": 0.93, "x1": 120, "y1": 200, "x2": 260, "y2": 480}, {"cls": "car", "conf": 0.89, "x1": 300, "y1": 150, "x2": 600, "y2": 400} ] for box in results: print(f"Detected {box['cls']} | Confidence: {box['conf']:.2f}") print(f"Location: ({box['x1']}, {box['y1']}) → ({box['x2']}, {box['y2']})") print("-" * 40) print("==== Lesson 6 Completed ====") |
esson 6 – Output (Text Only)
Example 6.1 – Output
Animal: cow
Animal: dog
Animal: cat
Example 6.2 – Output
Animal index: 0 | Name: cow
Animal index: 1 | Name: dog
Animal index: 2 | Name: cat
Example 6.3 – Output
Detected cow with confidence 0.92
Detected dog with confidence 0.85
Detected cat with confidence 0.88
Example 6.4 – Output
High confidence detection: cow (0.92)
Example 6.5 – Output
Detected: cow | Confidence: 0.92
Detected: dog | Confidence: 0.85
Detected: cat | Confidence: 0.88
Example 6.6 – Output
Matrix value: 1
Matrix value: 2
Matrix value: 3
Matrix value: 4
Matrix value: 5
Matrix value: 6
Matrix value: 7
Matrix value: 8
Matrix value: 9
Example 6.7 – Output
—- New Frame —-
Detected: cow | Confidence: 0.91
Detected: dog | Confidence: 0.87
—- New Frame —-
Detected: car | Confidence: 0.94
Detected: person | Confidence: 0.96
Example 6.8 – Output
Detection count: {'cow': 2, 'dog': 1, 'cat': 1}
Example 6.9 – Output
Filtered results: [{'cls': 'person', 'conf': 0.95}, {'cls': 'car', 'conf': 0.88}]
Example 6.10 – Output
Detected person | Confidence: 0.93
Location: (120, 200) → (260, 480)
Detected car | Confidence: 0.89
Location: (300, 150) → (600, 400)
example 7 : let see and understand A.I yolo real code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
# Learn Python to A.I Programming - Robotronix.co.il , Yaniv Maor # Example 7.1 – Detecting objects using YOLOv8 (real AI model) # ----------------------------------------------- from ultralytics import YOLO # Import YOLO library from Ultralytics print("Program start...") # Indicate program is running # Load the YOLOv8 small model (pre-trained on COCO dataset) model = YOLO("yolov8s.pt") # Run detection on a real image file results = model(r"C:\AI\PICS\pic1.png") # Display detections on the image window results[0].show() # --- Count cows using a loop --- count_cows = 0 # Start counter at zero # Go through every detected bounding box for box in results[0].boxes: cls_id = int(box.cls[0]) # Get the class ID (e.g., 0 = person, 20 = cow) label = model.names[cls_id] # Convert ID to readable name if label == "cow": # Check if detection is a cow count_cows += 1 print("Number of cows detected:", count_cows) # ----------------------------------------------- |
Program start…
image 1/1 C:\AI\PICS\pic1.png: 448×640 1 person, 3 cows, 1 sports ball, 427.0 ms
Speed: 20.1 ms preprocess, 427.0 ms inference, 22.9 ms postprocess per image at shape (1, 3, 448, 640)
Number of cows detected: 3
YOLO processed one image (C:\AI\PICS\pic1.png
) resized to 448×640 px and detected 1 person, 3 cows, and 1 sports ball in 427 ms.
It spent 20.1 ms loading/resizing (preprocess), 427 ms detecting (inference), and 22.9 ms filtering results (postprocess).
The model input shape (1, 3, 448, 640) means 1 image, 3 color channels, and the resized dimensions.
Finally, your loop found and printed “Number of cows detected: 3.”
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
# Learn Python to A.I Programming - Robotronix.co.il , Yaniv Maor # Example 8.1 – Detect and Count Only Cows (Real A.I. Model) # ---------------------------------------------------------- from ultralytics import YOLO # Import the YOLOv8 AI library print("Program start...") # Let the user know the program started # Load YOLOv8 model (trained on 80 object types, including 'cow') model = YOLO("yolov8s.pt") # Run the model on your image (make sure the file exists) results = model(r"C:\AI\PICS\pic1.png") # Show detections visually in a window results[0].show() # --- Count only cows using a loop --- count_cows = 0 # Start counter from zero # Go through all detected objects for box in results[0].boxes: cls_id = int(box.cls[0]) # Get numeric class ID (e.g., 0 = person, 20 = cow) label = model.names[cls_id] # Convert ID to readable label name if label == "cow": # Check if this detection is a cow count_cows = count_cows + 1 # Add 1 to the cow counter # Print how many cows were detected print("Number of cows detected:", count_cows) # ---------------------------------------------------------- |
Program start…
image 1/1 C:\AI\PICS\pic1.png: 448×640 1 person, 3 cows, 1 sports ball, 128.1 ms
Speed: 2.3 ms preprocess, 128.1 ms inference, 1.5 ms postprocess per image at shape (1, 3, 448, 640)
Number of cows detected: 3