[Tutor] 2 quick questions... [declarative/imperative programming]

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Wed, 2 Jan 2002 15:34:50 -0800 (PST)


On Wed, 2 Jan 2002 vip333d@yahoo.com wrote:

>  I want to make a somewhat simple program, that finds for me complex
> numbers, and does it by some algorithm that says:
>
> if N==2**(k-1)*(2**k-1)
> [NOT: N==2**(k-1)*(2**(k-1))]
> while 2**k-1 is a Number wich divides only with 1 and
> itself.

Python is an "imperative" language, which means that programming it in
involves telling Python _how_ to do something, step by step.


This may different from the math definitions that you may be familiar
with.  In math, one can declare that "k can be any number in the range(x,
y)".  This is "declarative" because the statement doesn't say exactly how
to go about finding k.


In contrast, imperative programming tells Python exactly how to find
things.  Here's an example of an declarative statement that might clarify
this distinction between "declarative" versus "imperative" programming:

    "A prime number 'n' has no factors except for 1 and itself."

How do we find out if a number 'n' is prime?  In imperative form, we need
to tell Python to actually search through the possibilities:

###
def isPrime(n):
    """Returns 1 if n is prime, and 0 otherwise."""
    for i in range(2, n):
        if n % i == 0:
            return 0
    return 1
###

which translates to the following idea: "Let's go through all the numbers
from 0 to n.  If any one of these numbers evenly divides n, then n must
not be prime!  Otherwise, if we exhaust the possibilities, n must be
prime."  The idea is the same, but expressed in such a way that we can
trace the calculation.



This is not to say that it's impossible to translate:

    "A prime number 'n' has no factors except for 1 and itself."

in Python: it just takes more work and a willingness to explain how to get
the factors of a number:

###
def getFactors(n):
    """Returns the factors of n, in ascending order."""
    factors = [1]
    for i in range(2, n):
        if n % i == 0:
            factors.append(i)
    factors.append(n)
    return factors

def isPrime(n):
    """Returns 1 if the only factors of n are 1 and n, 0 otherwise."""
    return getFactors(n) == [1, n]
###

And this definition of isPrime() works too.  Note that getFactors() itself
needs to explain, step by step, how to get the factors of a number.


Imperative programming can be a little weird at first, so please feel free
to ask questions.