04. Control Flow
If, Elif, Else
temperature = 0.8
if temperature < 0.3:
response_type = "creative"
elif temperature < 0.7:
response_type = "balanced"
else:
response_type = "focused"
print(f"Using {response_type} mode")
Ternary Expressions
For simple conditional assignment:
status = "success" if temperature < 1.0 else "failed"
For Loops
models = ["gpt-4", "gpt-3.5-turbo", "claude-3"]
for model in models:
print(f"Processing {model}")
Use enumerate() when you need the index:
for i, model in enumerate(models):
print(f"{i}: {model}")
While Loops
attempts = 0
max_attempts = 3
while attempts < max_attempts:
print(f"Attempt {attempts + 1}")
attempts += 1
Break and Continue
# Stop after finding the first match
for model in models:
if "gpt-4" in model:
print(f"Found: {model}")
break
# Skip invalid entries
valid_tokens = [0, 100, 200, None, 500]
total = 0
for tokens in valid_tokens:
if tokens is None:
continue
total += tokens
Checking Conditions
# Multiple conditions
if temperature > 0 and temperature < 1:
print("Valid temperature")
# Membership
if model in ["gpt-4", "gpt-3.5-turbo"]:
print("OpenAI model")
Local verification checkpoint
Run the smallest example from this chapter in a local workspace and record the package version, runtime, data path, and observed output. If the result depends on model size, vector count, CPU/GPU backend, or available memory, note that constraint beside the exercise so the lesson remains reproducible.
Local verification checkpoint
Run the smallest example from this chapter in a local workspace and record the package version, runtime, data path, and observed output. If the result depends on model size, vector count, CPU/GPU backend, or available memory, note that constraint beside the exercise so the lesson remains reproducible.
Write a script that loops through a list of temperature values [0.0, 0.5, 0.9, 1.2, 0.7] and prints whether each is "low", "medium", or "high" based on thresholds.