# CMU 15-110: Principles of Computing Loops

1. for loops
2. while loops
3. Infinite loops

1. for loops
• using range(n)
# print the integers from 0 to 9 (not 10) for x in range(10): print(x)

Example: sumToN
def sumToN(n): result = 0 for x in range(n+1): result += x return result print('n sumToN(n)') for n in range(10): print(n, ' ', sumToN(n))

• using range(lo, hi)
# print the integers from 20 to 29 for x in range(20, 30): print(x)

Example: factorial
def factorial(n): result = 1 for x in range(2, n+1): result *= x return result print('n factorial(n)') for n in range(10): print(n, ' ', factorial(n))

• using range(lo, hi, step)
# print the integers from 20 to 49 by 5's for x in range(20, 50, 5): print(x)

Example: sumOfOddsToN
def sumOfOddsToN(n): result = 0 for x in range(1, n+1, 2): result += x return result print('n sumOfOddsToN(n)') for n in range(10): print(n, ' ', sumOfOddsToN(n))

2. while loops
• leftmostDigit
def leftmostDigit(n): n = abs(n) while (n >= 10): n = n//10 return n print(leftmostDigit(72658489290098)) # 7

• digitSum
def digitSum(n): result = 0 n = abs(n) while (n > 0): onesDigit = n%10 n = n//10 result += onesDigit return result print(digitSum(201401)) # 2+0+1+4+0+1 == 8

3. Infinite loops
def addSomeNumbers(): total = 0 while True: rawInput = input('Enter a number (or just hit enter to quit) --> ') if (rawInput == ''): return total total += int(rawInput) total = addSomeNumbers() print('Total:', total)