[Tutor] Need help adding a funcation

Dave Angel d at davea.name
Thu Dec 1 16:51:01 CET 2011


On 12/01/2011 10:33 AM, Michael Hall wrote:
> Here is the code I have written.
>
> # Create main function.
> def main():
>      a = input('Please Enter a Number: ') # Ask user for input.
>      number = int(a)
>      x = 1
>      sum_of = 0
>      while number>  x:
>          if number % x == 0:
>              sum_of = sum_of + x
>          x += 1
>      if sum_of == number:
>         print(number,'is a Perfect Number')
>      elif sum_of<  number:
>         print(number,'is a Non-perfect Number')
>
> main()
>
> Here is the problem I am having. The program works perfect but I need to
> add the following:
>
> # a) write a function, getDivisors(), that returns a list of all
> # of the positive divisors of a given number. for example -
> # result = getDivisors(24)
> # print(result)
> # would yield: "[ 1, 2, 3, 4, 6, 8, 12]"
> # b) write a program that uses your function to determine which
> # numbers between 1 and 10,000 are perfect. (answer: 6, 28, 496
> # and 8128 are perfect!)
>
> I know that mystring needs to be added. I need help
> Thank you in advance
>
I don't see any 'mystring' in the source or in the assignment;   why 
would you think you need it?

It asks you to write a function called getDivisors().  You have all the 
pieces in your present code, but it's all inline.  Probably your 
professor wants you to learn to code in small functions, so your code is 
more likely to be reusable.

So what part of the function description is unclear?  And is it unclear 
because you don' t understand one of the math terms, or because you 
don't know how to code it?    She wants a function that takes a single 
argument (number), and returns a list

def getDivisors(number):
        do some stuff
        return mylist

You'll probably want to write another one that adds up the elements of a 
list (or you could find it in the stdlib).  Then your main should be 
pretty straightforward.



-- 

DaveA



More information about the Tutor mailing list