[Tutor] Help on a homework assignment
Alan Gauld
alan.gauld at yahoo.co.uk
Tue Sep 15 18:43:17 EDT 2020
On 15/09/2020 20:13, Jasmane Boyd wrote:
> gotten half of it working but the second part of it I can't get it to work.
I don't know where the halves start and stop but I'll pass some
comments that might help...
> #The following base code is given for you.
> from calculate_gains import calculate_gains
I've no idea what that does or how, since we don't have access to
the code, but I'll assume it just works..
> def calculate_gains_over_time(amount_inv=0.0, period=12):
> # calculate the first period before entering the loop
> calculate_gains(amount_inv)
Notice that this function does not return a result that
is stored anywhere. Any value that it returns is just
thrown away.
> # loop through the specified period to calculate the gain of each month
> for n in (list(range(1, period-1))):
You don;t need the list() because a for loop will work fine with the
bare range(). But are you sure you want period-1?
range(1,n) returns the numbers 1..n-1
So
range(1,n-1) returns 1...n-2
Is that really what you want?
> # 1 to period-1 because the first period gains is already calculated above
> calculate_gains(amount_inv)
Again you are not storing the result anywhere. amount_inv is
not defined anywhere so I'd expect that to give a name error.
It may be the name of the parameter of the function?
If so realize that the name is local to the function
and not visible outside. You need to store the return
value as a variable, pass that variable into the function
and store the result either in the same variable or
in another (depending on what exactly the functions do).
> # call the function to update the value based on the period inside the
> loop and the updated amount
> new_amount = total_amount # update the `new_amount` variable
You update new_amount but it is not defined anywhere.
Likewise you use total_amount but it is not defined either.
Maybe these are defined in the imported module?
If so they are internal to that module and not visible here.
The only name in the module that is visible is calculate_gains
because that's all you imported.
> # return the final ammount
> print(new_amount)
> #return new_amount
The comments suggest you return a value but in fact you print it.
The returned value will therefore be the Python default of None
> print(calculate_gains_over_time(amount_inv=4000000, period=12))
And here you print the returned value, ie. None
I think you need to do some reading on
a) how to import and use features in modules.
b) how to return values from functions and
c) how to use those function values in the caller.
And possibly also the rules of naming in Python
- especially local namespaces
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list