total =0
prices =[12.50,8.99,24.00]for price in prices:
total += price
print(f"Total: ${total:.2f}")for i inrange(3):print(f"Attempt {i +1}")
Output
Total: $45.49
Attempt 1
Attempt 2
Attempt 3
Note range(n) produces 0 through n-1. Use range(start, stop, step) for more control. Python for loops iterate over any iterable, not just numeric ranges.
for item in iterable:...else:# runs if loop completed without break
Example
targets =[2,4,6,8]for num in targets:if num %5==0:print(f"Found multiple of 5: {num}")breakelse:print("No multiple of 5 found")
Output
No multiple of 5 found
Note The else block runs only if the loop was NOT terminated by break. This is one of Python's most misunderstood features. Think of it as 'no-break'.
for elseloop else clauseno breakloop completed
Walrus Operator (:=)
Syntax
if(name := expression):
Example
data =[5,12,3,18,7,22]
high =[x for x in data if(doubled := x *2)>20]print(high)import re
text ="Order #12345 confirmed"if(match:= re.search(r"#(\d+)", text)):print(f"Order ID: {match.group(1)}")
Output
[12, 18, 22]
Order ID: 12345
Note The walrus operator (Python 3.8+) assigns and returns a value in one step. Most useful in while-loops, if-statements, and comprehensions to avoid repeated computation.
walrus operatorassignment expression:= operatorassign and check