[Tutor] Need help adding a funcation
Alan Gauld
alan.gauld at btinternet.com
Fri Dec 2 00:22:15 CET 2011
On 01/12/11 21:17, Michael Hall wrote:
> Can anyone else help with this question?
Sure lots of us could help. But Dave's doing a good job
leading you in the right direction.
Is there something that you don't understand? If you ask about specific
points we can give specific answers. Meantime I'll add a few extra
comments to see if that helps...
> def main():
> x = 1
>
> num = int(input('Please Enter a Number: '))
> getDivisors(num)
>
>
> You'll want to store the return value of getDivisors, since you have
> more work to do there.
What Dave means is that you are simply calling the function but not
storing the result. So you calculate the divisors but then have no
chance to use them. You need to store them in a variable someplace.
Think about the input() function you use above.
If you had just done
int(input('Please Enter a Number: '))
You couldn't use the value that the user entered.
You had to assign it to num to do that. It's the same
with your function getDivisors()
> def getDivisors(num):
> sum = 0
> x = 1
> #my_list[] = num
>
> That's close. To create an empty list, simply do
> my_list = []
self explanatory, I hope.
> for num in range(1, num, 1):
>
> if num % x == 0:
> print(num)
> sum += num
>
> Why are you summing it? That was in another function. In this one,
> you're trying to build a list. Any ideas how to do that at this
> point in the function?
So you need to store your results as a list not as a number. So instead
of sum() what can you do to my_list to add a new element?
If you aren't sure fire up the Python >>> prompt and try
help(list) or just help([]) and see if you can see anything useful.
> print('The sum is ', sum)
> if sum == num:
> print(num, 'is a perfect number')
> else:
> print(num, 'is not a perfect number')
>
> None of these lines belong in your function. All it's supposed to
> do is get the divisors, not to study them in any way.
This is a good principle to apply when writing functions. Separate out
the display from the logic. That way you can use the results of the
logic with any kind of user interface - GUI, Web, or command line, or
even in a server process without a UI.
But this takes us back to the advice to assign the result to a variable
in main().
To do that you need to return a result. And in this case your result
should be a list of numbers. then you can do any printing in the main
function.
HTH,
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list