How to add interest to a bank account balance once a month? - python

I have to create a bankaccount class that has functions such as: deposit, withdraw, getbalance; all that beginner stuff. All very easy and I finished it no problem. However, there is a function called Interest that takes in an interest_rate where I am running into a lot of trouble. To explain, this function is supposed to add interest per the user's request only once a month to the balance of the bankaccount. So let's say I decide to add 5% interest on today's date (Oct 13) to my balance. The function would execute and spit out my new balance. Then let's say I want to add 10% interest the next day (Oct 14th), the function would not execute and would spit out something like "Cannot add interest until Nov.1", which is the first of the next month. On Nov.1, if I tried to add 10% interest, I would succeed and then if on Nov. 2 I tried to add interest again, it would say "Cannot add interest until Dec.1" so on and so forth. I'm having a very hard time with this. Below is the code that I wrote, however it would not only ever execute because the date will always be ahead a month, but it would also always add interest to the balance.
Here's what I have so far, but it's a mess. Anyone have any tips on what I should do? I know it's not inside a function the way it's supposed to be in the assignment but I thought I would figure out the main picture of the program first and then worry about incorporating it into the rest of my class.
from datetime import *
from dateutil.relativedelta import *
rate = 0.10
balance = 1000.00 # i just made up a number for the sake of the code but the
# balance would come from the class itself
balancewInterest = rate*balance
print(balancewInterest)
# this is where I'm having the most trouble
todayDate = date.today()
print(todayDate)
todayDay = todayDate.day
todayMonth = todayDate.month
if todayDay == 1: # if it's the first of the month, just change the month
# not the day
nextMonth = todayDate + relativedelta(months=+1)
else: # if not the 1st of the month, change day to 1, and add month
nextMonth = todayDate + relativedelta(months=+1, days=-(todayDay-1))
print(nextMonth)
difference = (todayDate - nextMonth)
print(difference.days)
if todayDate >= nextMonth: # add interest only when it's the first of the next
# month or greater
interestPaid = rate*balance
print(interestPaid)
else:
print("You can add interest again in " + str(abs(difference.days)) \
+ " days.")

I have now completed how to do it.
import datetime
import os
import time
x = datetime.datetime.now()
try:
s = open("Months.txt","r")
ss = s.read()
s.close()
except IOError:
s = open("Months.txt","w")
s.write("Hello:")
s.close()
try:
Mo = open("Deposit and interest.txt","r")
Mon = Mo.read()
Mo.close()
except IOError:
Deposit = input("How much do you wish to deposit")
M = open("Deposit and interest.txt","w")
M.write(Deposit)
M.close()
s1 = open("Months.txt","r")
s2 = s1.read()
s1.close()
Mone = open("Deposit and interest.txt","r")
Money = Mone.read()
Mone.close()
if s2 != x.strftime("%B"):
Rate = input("How much interest do you want?")
Deposit1 = int(Money)/int(100)
Deposit2 = Deposit1*int(Rate)
Deposit = int(Money) + int(Deposit2)
print("Calculation of interest")
time.sleep(2)
print("The final total is: "+str(Deposit))
os.remove("Months.txt")
file_one=open("Months.txt","w")
file_one.write(x.strftime("%B"))
file_one.close()
os.remove("Deposit and interest.txt")
file_one=open("Deposit and interest.txt","w")
file_one.write(str(Deposit))
file_one.close()
print("Used up this month, try again next month")
else:
print("Sorry, you have used this months intrest limit, try again next month")

def calculate_interest(amount_deposited, time):
rate_of_interest = 5
int rest = (amount_deposited*time*rate)
return int rest
print(calculate_interest(1000, 2))
''' for eg: here 1000 is the amount deposited and for 2 years at the rate of interest 5.'''

Related

Why is my function not getting called properly?

I'm writing a program that will greet somebody (given name) and then ask them how many hours they worked and how much their hourly pay is. The program runs but is not spitting back the correct math. I'm getting this for my answer... you earned<function wage at 0x00EA9540>
I have already tried calling payment but not getting an answer with that either.
def greet(greeting):
name = input("Hi, whats your name?")
return greeting + name
print(greet ("Hey "))
hourly = input("How much is your hourly wage?")
hours = input("How many hours did you work this week?")
def wage(hourly, hours):
if hours > 40:
payment = 40 * hourly
payment = payment + hourly * (hours-40) * 1.5
return payment
else:
return hours * hourly
print("you earned" + str(wage))
You missed the parameters to the wage function.
in your case, it just prints the memory address of the function wage...
you need to change the print call with the correct parameters to the wage function:
print("you earned" + str(wage(hourly, hours)))
You need to call the wage function with the parameters:
print("you earned" + str(wage(hourly, hours)))
Otherwise you are simply printing the string representation of the wage function object, and that doesn't really make much sense.

Python - Passing variables through functions

I am about a week into Python. I have looked at various other questions regarding this, and have grown fairly frustrated that my attempts to implement those suggestions are falling flat.
I have tried a few means of passing variables through, based on things I have read. For example (this isn't necessarily representative of a coherent attempt... I have tried many variations and have had to walk back to get code worth posting):
def verify_nums():
globhours = hours
globrate = rate
try:
globhours = float(globhours)
globrate = float(globrate)
return globhours,globrate
except:
print("You must provide numbers")
def calc():
globhours = globhours
globrate = globrate
if globhours > 40:
base = 40 * globrate
ot = (globhours - 40) * (globrate * 1.5)
pay = base + ot
print(pay)
else:
pay = globrate * globhours
print(pay)
hours = input("Enter hours worked: ")
rate = input("Enter hourly rate: ")
verify_nums()
calc()
I am supremely confused on how to transfer the hours and rate variables over to the calc() function.
I eventually figured out I could just merge these into one function...
def paycalc(hours,rate):
etc.
etc.
hours = input("Enter hours: ")
hours = input("Enter hours: ")
paycalc(hours,rate)
But for the sake of learning, I really want to get this global/local thing figured out.
Thanks for the help!
You seem to be trying to get Python to guess which functions are supposed to be global and which local based on their names. Python doesn't do that. If you assign to a variable in a function, and you want that assignment to be global, you need a global statement at the top of the function:
def verify_nums():
global globhours
global blograte
globhours = hours
globrate = rate
# ...
Also, globhours = globhours doesn't do anything useful—and, in fact, it causes a problem. If you global globhours in that function as well, the statement is meaningless. Without that, you're creating a local variable, and assigning it… the value of that local variable that doesn't exist yet.
Anyway, if you add the right global declarations to all of your functions, they will work, but it won't be a great design.
You really don't need any global variables here. If you think about values rather than variables, everything gets a lot easier.
Your verify_nums function needs to work on two values. So just pass those values in as parameters. And it needs to return two values—that's easy, you already did that part.
Now the caller has to store those two values that it returned, so it can pass them to the calc function. Which can also take two values as parameters.
Putting that all together:
def verify_nums(hours, rate):
try:
numhours = float(hours)
numrate = float(rate)
return numhours, numrate
except:
print("You must provide numbers")
def calc(hours, rate):
if hours > 40:
base = 40 * rate
ot = (hours - 40) * (rate * 1.5)
pay = base + ot
print(pay)
else:
pay = rate * hours
print(pay)
globhours = input("Enter hours worked: ")
globrate = input("Enter hourly rate: ")
hours, rate = verify_nums(globhours, globrate)
calc(hours, rate)
One problem left: what happens if there's an error with the user's input? Inside verify_nums, you handle the error with an except:, then you print a message and do nothing. That means you return None. So, when the caller tries to do hours, rate = None, it's going to get an error, which you're not handling. And you can't just carry on without values. What can you do?
More generally "return a pair of numbers, or return None" is a confusing contract for a function to fulfill. How do you use that function? With a whole lot of ugly type-checking. But "return a pair of numbers, or raise an exception" is a perfectly good contract. How do you use that function? With a simple try.
That's why it's better to put the exception handling in exactly the right place where you can deal with it. You want to skip calling calc if there's an error, so the except has to be where you call calc.
def verify_nums(hours, rate):
numhours = float(hours)
numrate = float(rate)
return numhours, numrate
def calc(hours, rate):
if hours > 40:
base = 40 * rate
ot = (hours - 40) * (rate * 1.5)
pay = base + ot
print(pay)
else:
pay = rate * hours
print(pay)
try:
globhours = input("Enter hours worked: ")
globrate = input("Enter hourly rate: ")
hours, rate = verify_nums(globhours, globrate)
except ValueError:
print("You must provide numbers")
else:
calc(hours, rate)
Another improvement you might want to consider: Have calc return the pay, instead of printing it, and make the caller print the value it returns.

Working with commas in output

I'm in an intro programming class and am lost. We've had several labs that required knowledge that we haven't been taught but I've managed to find out what I need on google (as nobody responds to the class message board) but this one has me pretty frustrated. I'll include a pastebin link here: https://pastebin.com/6JBD6NNA
`principal = input()
print('Enter the Principal Value of your investment: $', float(principal))
time = input()
print('\nEnter the Time(in years) you plan to save your investment: ', int(time))
rate = input()
print('\nEnter the Rate (2% = 0.02) you will collect on your investment: ', float(rate))
interest = (float(principal) * float(rate)) * int(time)
final_value = float(principal) + float(interest)
print('\nThe Final Value of your investment will be: $%.2f' % final_value)`
So I need the output of the dollar amounts to have a comma ($27,500.00) but I have no idea how to do this. I've seen a couple of solutions on this site and others but I can't get them to work. PLEASE can someone help me?
In Python 2.7 or above, you can use
print('The Final Value of your investment will be: ${:,.2f}'.format(final_value))
This is documented in PEP 378.
Source: Python Add Comma Into Number String
Here is a working example:
principal = float(input('Enter the Principal Value of your investment: $'))
time = int(input('\nEnter the Time(in years) you plan to save your investment: '))
rate = float(input('\nEnter the Rate (2% = 0.02) you will collect on your investment: '))
interest = principal * rate * time
final_value = principal + interest
print('The Final Value of your investment will be: ${:,.2f}'.format(final_value))
Your last line should be:
print ("\nThe Final Value of your investment will be: ${:,.2f}".format(final_value))

Python car sales code issue

Ok so, I have an assignment to make a carsales program which is suppose to calculate how much the salesperson will make in a week. I already know how much all the cars sell for and how much commission he makes. Here is my code:
def main():
print ('This program will compute the comission earned for the week based on your sales for the week.')
car_number = float(input('Enter number of cars sold :'))
def calculate_total(car_number,price,commission_rate):
price = 32,500.00
commission_rate = .025
calculate_total = car_number * price * commission_rate
return calculate_total(car_number)
print('The weekly gross pay is $',calculate_total)
main()
The program isn't working for some reason but I decided to submit it to my professor anyway. He then replied by saying that I wasn't asked to create a new function and that I have to delete it and work just in main. Can someone please tell me what this means?
Two things:
'Working in main' as your professor said means that you don't define any functions. All your code just sits in the file, without any def ... statements. I know that's probably not clear. Here's an example:
import os
print "Your current working directory is:"
print os.getcwd()
This kind of programming has more the feel of a 'script' - you're not defining parts of the program that you're going to use more than once, and you're not taking the trouble to break down what the program does into single-purpose functions.
Second, you've entered price in such a way that Python thinks you're creating a tuple of numbers instead of a single value.
price = 32,500.00 is interpreted by Python as creating a tuple, with values 32 and 500.00 in it. What you actually want is: price = 32500.00.
I broke down and completed the process for you.
print ('This program will compute the comission earned for the week based on your sales for the week.')
car_number = float(input('Enter number of cars sold :'))
price = 32500.00
commission_rate = .025
calculate_total = car_number * price * commission_rate
print('The weekly gross pay is $',calculate_total)
Sorry i did not saw the complete question before but anyway this is the correct answer without a function
The keywords try and except are for error handling. If you give as input something invalid let's say a letter instead of number will throw a message
(Could not convert input data to a float.)
def main():
print ('This program will compute the comission earned for the week based on your sales for the week.')
try:
#before: car_number = float(raw_input('Enter number of cars sold :'))
car_number = float(input('Enter number of cars sold :'))
except ValueError:
#before: print 'Could not convert input data to a float.'
print('Could not convert input data to a float.')
print('The weekly gross pay is ${}'.format(car_number * 32500.00 * 0.025 )))
main()
If you don't even want main() function here is the answer:
print ('This program will compute the comission earned for the week based on your sales for the week.')
try:
car_number = float(input('Enter number of cars sold :'))
except ValueError:
print('Could not convert input data to a float.')
print('The weekly gross pay is ${}'.format(car_number * 32500.00 * 0.025 )))

global name 'getYearlyCost2' is not defined

I'm using python for the very first time and I am stuck on this stinking problem and cant for the life of me figure out why its not working. When I try and run my program I can get an answer for the yearly cost without the modification (even though its wrong and I dont know why) but not the yearly cost with the modification.
I've tried rewriting it in case I missed a colon/parenthesis/ect but that didnt work, I tried renaming it. And I tried taking it completely out (this is the only way I could get rid of that annoying error message)
payoff file
from mpg import *
def main():
driven,costg,costm,mpgbm,mpgam = getInfo(1,2,3,4,5)
print("The number of miles driven in a year is",driven)
print("The cost of gas is",costg)
print("The cost of the modification is",costm)
print("The MPG of the car before the modification is",mpgbm)
print("The MPG of the car afrer the modification is",mpgam)
costWithout = getYearlyCost(1,2)
print("Yearly cost without the modification:", costWithout)
costWith = getYearlyCost2()
print("Yearly cost with the modification:", costWith)
While I know there is an error (most likely a lot of errors) in this I cant see it. Could someone please point it out to me and help me fix it?
Also I added my mpg.py in case the error is in there and not the payoff file.
def getInfo(driven,costg,costm,mpgbm,mpgam):
driven = eval(input("enter number of miles driven per year: "))
costg = eval(input("enter cost of a gallon of gas: "))
costm = eval(input("enter the cost of modification: "))
mpgbm = eval(input("eneter MPG of the car before the modification: "))
mpgam = eval(input("enter MPG of the car after the modification: "))
return driven,costg,costm,mpgbm,mpgam
def getYearlyCost(driven,costg):
getYearlyCost = (driven / costg*12)
def getYealyCost2(driven,costm):
getYearlyCost2 = (driven / costm*12)
return getYearlyCost,getYearlyCost2
def gallons(x,y,z,x2,y2,z2):
x = (driven/mpgbm) # x= how many gallons are used in a year
y = costg
z = (x*y) # z = how much money is spent on gas in year
print("money spent on gas in year ",z)
x2 = (driven/mpgam) # x2 = how much money is spent with mod.
z2 = (x2*y)
y2 = (costm + z2)
1,1 Top
Here's your immediate problem:
costWith = getYearlyCost2()
The function you're trying to call is named getYealyCost2() (no "r").
There are other problems that you'll find as soon as you fix that, such as no return statement in getYearlyCost() and trying to return the function getYearlyCost() in getYearlyCost2() and calling getYearlyCost2() without any arguments.
On top of that, import * is frowned upon, and then there's the use of eval()... but that'll do for starters.

Categories