Using for and range() for looping


# to print out numbers from 0 to 10:
for i in range(11):
    print(i)
    
# to print out numbers from 5 to 12:
for i in range(5,13):
    print(i)
    
# to add up the numbers from 1 to 100:
total = 0
for i in range(1,101):
    total += i

# using "break" to add up the numbers from 1 to 100:
total = 0
for i in range(1,100000000):
    total += i
    if i == 100:
        break

# Create a function addToLCM(fred,george) which adds up all the numbers from 1 until the
#    first number that is evenly divisible by both fred and george:
# We know that the number fred*george is evenly divisible by both fred and george, but a
#   smaller number may also be (for instance if fred = 4 and george = 8, then the smallest
#   number evenly divisible by 4 and 8 is 8, not 32).

def addToLCM(fred,george):
    total = 0
    for i in range(1,fred*george+1):
        total += i
        if i % fred == 0 and i % george == 0:
            break
    return total

# Create a function that shows that the sum of the numbers from 1 to N equals N*(N+1)/2
def proveIt(N):
    total = 0
    for i in range(N+1):
        total += i
    print(total,'should be',N*(N+1)/2)
    

# we know that sum: 1/2 + 1/4 + 1/8 + 1/16 + ... gets closer and closer to 1.0.
# Create a function howMany(teeny) that will tell us how many terms we need to add so that
#  the sum is closer to 1 than teeny.  Assume that teeny is very small.
def howMany(teeny):
    total = 0
    for i in range(1,1000000):
        total += 1/(2**i)
        if abs(1 - total) < teeny:
            return i