Main.WhileLoops History

Hide minor edits - Show changes to markup

February 07, 2013, at 02:35 PM MST by 129.82.44.223 -
Added lines 1-40:

(:source lang=python:)

"""Examples of iteration using the while statement"""

def num_digits(n) :

    """counts the number of digits in a number"""
    count = 0
    while n > 0 :
        count = count + 1
        n = n // 10
    return count

def countdown(n) :

    while n > 0 :
        print n
        n = n-1
    print "Blastoff!"
  1. what does this function do?

def countup(n) :

    while (n > 0) :
        print n
        n += 1      # same as n = n + 1
  1. Use ctrl-C to stop any program
  2. let's look at this one:

def ulam(n):

    while n != 1:
        print n,
        if n % 2 == 0:        # n is even
            n = n // 2
        else:                 # n is odd
            n = n * 3 + 1

(:sourceend:)