class - Python returning and passing variables -
i’m trying create program to:
- randomly generate account balance;
- assess whether balance meets minimum balance requirement of 10;
- if does, print string stating “no minimum balance fees apply”, or;
- if not, assess fine of 10 , print net balance after fine.
here code:
from random import randint class calculate(object): def __init__(self, account_balance): self.account_balance = account_balance def applycharge(self): account_balance = self.account_balance if account_balance < 10: print "minimum balance charges of $10 apply." account_balance = account_balance - 10 print account_balance return account_balance else: print "no minimum balance charges apply." def printbalance(self): account_balance = self.account_balance print "the net account balance is: %d" % account_balance initial_balance = randint(-100, 100) print "the account balance before charges is: %d" % initial_balance getcharge = calculate(initial_balance) getcharge.applycharge() getcharge.account_balance() when run it, here example of get:
the account balance before charges is: -74 minimum balance charges of $10 apply. -84 net account balance is: -74 so, going ok until last line. (and ok when randomly-generated balance not lower 10, causes fine assessed.)
note - put print statement in displays next-to-last line (-84) check fine point.
the problem comes in when want display “net account balance”. displaying original balance, before fine of 10 assessed.
i assume there problem in how returning balance after fine , passing “printbalance” method. or not passing it, appears case. alternatively, may have using original, global variable when “printbalance” invoked, rather trying do, change value, return , display it.
my whole point in writing little piece of code exercise brain in passing variables around , try flesh out do not understand. mission accomplished.
i’m going stop there, because explanation become tangled spaghetti-bowl of gibberish brain right now, hope gives enough info make clear trying accomplish.
i did @ other similarly-worded questions/answers not seem answer out of them.
finally, i'm sure there kinds of things wrong here - i've been programming (or trying to) 3 weeks.
you return new balance, ignore returned value, nor did set new value on instance.
as such, account_balance value return lost, ignored.
you wanted update attribute, getcharge.printbalance() print updated value:
def applycharge(self): account_balance = self.account_balance if account_balance < 10: print "minimum balance charges of $10 apply." self.account_balance = account_balance - 10 else: print "no minimum balance charges apply." i removed return line; getcharge instance of calculate class responsible tracking account balance value.
Comments
Post a Comment