Loops and Conditionals
To make decisions and repeat actions, Python uses conditionals (
if, elif, else) and loops (for, while). These are the building blocks of logic in any AI program.Conditionals (if‑elif‑else)
Execute code only when a condition is True.
accuracy = 0.95
if accuracy > 0.9:
print("Great model!")
elif accuracy > 0.7:
print("Good enough")
else:
print("Need improvement")For Loops – Iterate Over Sequences
Used to process lists, arrays, or ranges of numbers.
# Loop through a list of features
features = ["age", "income", "score"]
for f in features:
print(f"Processing {f}")
# Loop 5 times
for i in range(5):
print(i)While Loops – Repeat Until Condition Changes
Use when you don’t know the number of iterations in advance.
epoch = 0
while epoch < 10:
print(f"Epoch {epoch}")
epoch += 1Why Loops and Conditionals Are Vital for AI
- Training loops: Iterate over epochs and batches.
- Data filtering: Use conditionals to select relevant data.
- Early stopping: Break a loop when validation loss stops improving.
Two Minute Drill
if condition: ... elif ... else ...for decisions.for item in list:iterates over each item.for i in range(n):repeats n times.while condition:repeats until condition False.
Two Minute Drill
if condition: ... elif ... else ...for decisions.for item in list:iterates over each item.for i in range(n):repeats n times.while condition:repeats until condition False.
Need more clarification?
Drop us an email at career@quipoinfotech.com
