Python Cheat Sheet
Python Cheat Sheet
Example 3:
• Write a loop to evaluate this summation series given n:
n
1
∑ i(i+1)
i=1
sum = 0
for i in range(1, n+1):
sum += 1/(i*(i+1))
Example 4:
• Write a loop to evaluate this summation series to 8 decimal places:
❑
1
∑ i(i+1)
i=1
Summation Series 2
sum = 0
eps = 1e-8
i = 1
term = 1/2 # = 1/(1*(1+1)) for first term
while term > eps:
sum += term
i += 1
term = 1/(i*(i+1))
Nested loops
• The inclusion of a loop inside another
sum = 0
sum += i * j
Infinite loop
• Sometimes this is deliberate, but with a condition within the loop that allows breaking
out
Break
• Stops the computation in a loop and forces exit from the loop
• In a nested loop situation, a break statement breaks out of the loop directly containing
it.
Summation Series 4
sum = 0
eps = 1e-8
i = 1
term = 1/2 # = 1/1*(1+1) for first term
while True:
sum += term
i += 1
term = 1/(i*(i+1))
if term < eps:
break
continue
• Stops the computation in a loop and return to the top of the loop
• In a nest loop situation, a continue statement returns to the top of the loop directly
containing it.
for … else (and while … else too)