
# Python's built-in range function generates a list
print range(10) # generates [0,1,2,3,4,5,6,7,8,9]
print range(1,5)  # generates [1,2,3,4]
print range(1,10,2)  # generates [1,3,5,7,9]

# print the alphabet
# uses built-in functions chr() and ord()
for k in range(ord('a'), ord('z') + 1):
	print chr(k)# print the alphabet

# Running total algorithm using a simple for loop
# Accumulate the partial total in 'sum'
sum = 0
for k in [1,2,3,4,5]:   # Lists in Python are enclosed in square brackets
	print 'k=',k
	print 'So far the sum is ', sum
	sum = sum + k
print 'The sum = ', sum

# Computes the sum from 1 to n, inclusive
# using a running total algorithm
def sum(n):
#	print (n * (n+1))/2  # Closed form equation for sum of 1..n
	sum = 0                  
	for k in range(n+1):
		sum = sum + k
	print 'The sum of 1 to ', n, ' is ', sum
# Test the function
sum(3)
sum(5)
sum(10)
	
# Computes the sum of even numbers between from 1 to n, inclusive
# using a running total algorithm
def sumEvens(n):
	sum = 0
	for k in range(2,n+1,2):
		sum = sum + k
	print 'The sum of evens up to  ', n, ' is ', sum
# Test the function
sumEvens(3)
sumEvens(5)
sumEvens(10)
	
# Computes the factorial of n using a running total algorithm
def factorial(n):
	product = 1
	for k in range(1,n+1):
		product = product * k
	print 'The factorial of ', n, ' is ', product
# Test the factorial
factorial(0)
factorial(3)
factorial(5)

# Computes x to the nth power, for n >= 0
# using a running total algorithm
def power(x,n):
	product = 1
	for k in range(n):
		product = product * x
	print x, ' raised to the ', n, ' power is ', product
# Test the power function
power(3,0)
power(3,2)
power(3,4)


