- 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))