Arithmetic not being done on first dictionary entry? - python

class creditCard:
def __init__(self, limit, apr, balance):
self.limit = limit
self.apr = apr
self.balance = balance
self.charges = {}
self.payments = {}
def charge(self, amount, day):
# Charges the card, and stores the charge and day the charge was made in a dictionary.
# Returns false if the amount charged is greater than the limit.
if amount > self.limit - self.balance:
return False
self.charges[day] = amount
self.balance += amount
def payment(self, amount, day):
# When a payment is made the payment is stored in the payments dictionary with the corresponding day.
# Returns false is the payment amount is greater than the balance owed/limit.
if amount > self.limit - self.balance:
return False
self.payments[day] = amount
self.balance -= amount
def interest(self, balance):
# calculates and returns interest
return (balance * self.apr) / 365
def days_balance(self, balance_day):
balance_to_date = 0
months_interest = 0
for day in range(1, balance_day+1):
balance_to_date += self.charges.get(day, 0)
balance_to_date -= self.payments.get(day, 0)
months_interest += self.interest(balance_to_date)
if day % 30 == 0:
balance_to_date += months_interest
months_interest = 0
balance_to_date = round(balance_to_date, 2)
return "${}".format(balance_to_date)
I am supposed to be returning 411.99 for my second test case and I am getting 411.89 due to the dictionary not applying the interest for the first day. I can not figure out why it is doing that what so ever. Any help would be greatly appreciated. Below is my test case.
customer opens a credit card with 1k limit and 35% APR
customer charges $500 on opening day
15 days after opening he pays $200 (balance now 300)
25 days after opening he charges another $100 (balance now 400)
total balance at the end of the month is 411.99
customer1 = creditCard(1000, 0.35, 0)
customer1.charge(500, 1)
print(customer1.days_balance(30))
for i in customer1.charges:
print(customer1.charges.keys(), customer1.charges.values())
customer2 = creditCard(1000, 0.35, 0)
customer2.charge(500, 1)
customer2.payment(200, 15)
customer2.charge(100, 25)
print("Customers Balance on Day 26: " + customer2.days_balance(26))
print("Customers Balance on Day 30 with Interest: " +
customer2.days_balance(30))

Related

how to execute a class with some condition statements in python?

#Making a program "(subscribing for an entertainment)like Netflix" that would ask for users name then age.before they enter they should be on a legal age then if not print ("sorry you are not allowed to have a subscription").
If not. The code will continue then will ask for the users for their amount of money that they will pay and the higher the money the higher the discount price. Then will also asked how many months they will subscribe for the entertainment restricted (1,3,6,12 only) else the program will stop.
class Entertainment:
def __init__(self, subscription, price, term):
self.subscription = subscription
self.price = price
self.term = term
nameUser = input("Your name is,")
ageUser = int(input("Age:"))
if ageUser < 13:
return total_amount
subscription = float(input("Money Available: "))
if subscription <= 100:
price = subscription - 0.5
elif subscription in range(101 - 200):
price = subscription - 0.10
elif subscription in range(201 - 300):
price = subscription - 0.15
elif subscription >= 400:
price = subscription - 0.20
def MonthlySubs():
# Making this strictly 1,3,6,12 only and other numbers will not be accepted
use_months = float(input("(1,3,6,12) Only "))
if use_months == 1:
return price / 1
elif use_months == 3:
return price / 3
elif use_months == 6:
return price / 6
elif use_months == 12:
return price / 12
else:
print("Invalid Months of subscription")
break
#MAKING SOMETHING LIKE HOW PEOPLE SUBSCRIBE FOR PREMIUM BENEFITS
#problem is I don't understand how I will make these conditions connect to become a whole program
# Help me how I will have an output like this using classes:
>#Name: Mitchel
> #Age: 21
> #Money: 200
> #subscription months = 3
> #your payment amount is 209.5

calculate mortgage in python?

so i have this program that calculate that calculates the total amount that Dave will have to pay over the life of the mortgage:
# mortgage.py
principal = 500000.0
rate = 0.05
payment = 2684.11
total_paid = 0.0
while principal > 0:
principal = principal * (1+rate/12) - payment
total_paid = total_paid + payment
print('Total paid', total_paid)
and later the exercise ask me Suppose Dave pays an extra $1000/month for the first 12 months of the mortgage?
Modify the program to incorporate this extra payment and have it print the total amount paid along with the number of months required.
what can i modify to make the changes to the program ? I am lost
principal=500000.0
rate= 0.0
payment = 2684.11
total_paid = 0.0
extra_payment = 1000.0
num_periods = 0
while principal > 0:
if num_periods < 12:
principal = principal * (1+rate/12) - (payment+extra_payment)
total_paid += payment + extra_payment
else:
principal = principal * (1+rate/12) - (payment)
total_paid += payment
num_periods += 1
print('Total paid: $', total_paid)
Total paid = 929965.6199999959,
but principal = -1973.205724763917
You have overpayed the final payment
remember to add 'principal' to 'total_paid' to get the actual amount:
927992.414275232
Also, the numbers are not rounded to 2 decimal places
you can round them by using:
def twoDecimalPlaces(answer):
return("%.2f" % answer)
twoDecimalPlaces(927992.414275232)
>>> 927992.41
Here you need to ask again to the user "Do Dave has paid anything extra in principal amount?" if Yes then create new variable for updated principal
update_principal = principal + dave_paid_extra
and then re run the code with same eqaution.

My variable is coming back as undefined in Python

I am trying to challenge myself by creating a program from scratch to help work out errors, etc.
So I did a simple stamp shop which has different values for various books of stamps. I now want to calculate the price per piece after collecting taxes. I have tried to setup an if/elif/else statement to calculate the price per stamp. Here is the code that I have so far.
'''
# what is the price per stamp including taxes
number_of_stamps_purchased = 10
# calculate government sales taxes on stamps 13%
sales_tax = 0.13
# number of stamps in each booklet
single_stamp = 1
book_of_five = 5
book_of_ten = 10
book_of_fifteen = 15
book_of_twenty = 20
# pricing chart for each book of stamps
single = 1.50
five = 7.00
ten = 10.00
fifteen = 14.00
twenty = 16.00
# price list for customers
print('''Welcome to my stamp shop!
Please review our price list:
Single Stamp $1.50
Book of 5 Stamps $7.00
Book of 10 Stamps $10.00
Book of 15 Stamps $14.00
Book of 20 Stamps $16.00
(Does not include sales tax)''')
# conditions for total price calculation of stamps purchased
def stamp_cost(price_per_piece):
if number_of_stamps_purchased <= 4:
print('''
Your stamp cost:''',((single * sales_tax / single_stamp) + single) * number_of_stamps_purchased)
elif number_of_stamps_purchased == 5:
print('''
Your stamp cost:''',((five * sales_tax) + five))
elif number_of_stamps_purchased == 10:
print('''
Your stamp cost:''',((ten * sales_tax) + ten))
elif number_of_stamps_purchased == 15:
print('''
Your stamp cost:''',((fifteen * sales_tax) + fifteen))
elif number_of_stamps_purchased == 20:
print('''
Your stamp cost:''',((twenty * sales_tax) + twenty))
else:
print('Error')'''
# calculate the per piece price based on their savings when purchasing a book
print(total_price / number_of_stamps_purchased)
'''
You never declare a variable with the name total_price, so when you try and print with print(total_price / number_of_stamps_purchased) Python warns you about never defining it. You can fix this by defining a total_price before the last line. Perhaps like so:
def stamp_cost(): # I have removed the argument as it was unused.
if number_of_stamps_purchased <= 4:
total_price = ((single * sales_tax / single_stamp) + single) * number_of_stamps_purchased
print('''
Your stamp cost:''', total_price)
# The rest of the function with the same modification
return total_price
total_price = stamp_cost()
print(total_price / number_of_stamps_purchased)
Something like that should work a little better. The main problem as it as been previously pointed is that you never call your fonction stamp_cost. So, what you need to do is affect the result of what you are doing with stamp_cost to your variable total_price.
# calculate government sales taxes on stamps 13%
sales_tax = 0.13
# pricing chart for each book of stamps
single = 1.50
five = 7.00
ten = 10.00
fifteen = 14.00
twenty = 16.00
# number of stamps in each booklet
single_stamp = 1
book_of_five = 5
book_of_ten = 10
book_of_fifteen = 15
book_of_twenty = 20
# price list for customers
print('''Welcome to my stamp shop!
Please review our price list:
Single Stamp $1.50
Book of 5 Stamps $7.00
Book of 10 Stamps $10.00
Book of 15 Stamps $14.00
Book of 20 Stamps $16.00
(Does not include sales tax)
''')
# conditions for total price calculation of stamps purchased
def stamp_cost():
if number_of_stamps_purchased <= 4:
total_price = (single * sales_tax / single_stamp + single) * number_of_stamps_purchased
print('Your total cost:', total_price)
elif number_of_stamps_purchased == 5:
total_price = five * sales_tax + five
print('Your total cost:',total_price)
elif number_of_stamps_purchased == 10:
total_price = ten * sales_tax + ten
print('Your total cost:', total_price)
elif number_of_stamps_purchased == 15:
total_price = fifteen * sales_tax + fifteen
print('Your total cost:',total_price)
elif number_of_stamps_purchased == 20:
total_price = twenty * sales_tax + twenty
print('Your total cost:',total_price)
else:
print('Error')
return total_price
number_of_stamps_purchased = 10
print('Number of stamp purchase:',number_of_stamps_purchased)
total_price = stamp_cost()
# calculate the per piece price based on their savings when purchasing a book
print('Price per piece:',round(total_price / number_of_stamps_purchased,2))

MIT opencourseware - stuck on a basic issue, credit card minimum payment over a year calculation

Basically I'm pretty stuck on this issue, I've linked the question below, it's part 'b' I'm stuck on, or the second question in the document:
http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00sc-introduction-to-computer-science-and-programming-spring-2011/unit-1/lecture-4-machine-interpretation-of-a-program/MIT6_00SCS11_ps1.pdf
If I'm honest it's just got to the point where I'm totally confused! I've put my code below:
balance = float(raw_input('Vot is the outstanding balance? '))
InrAn = float(raw_input('Vot is the annual interest rate as a decimal? '))
month = 1
monthPay = 10
monthInr = InrAn/12.0
newBalance = balance
while balance > 0:
newBalance = newBalance * (1 + monthInr) - monthPay
month +=1
if month > 12:
month = 1
newBalance = balance
monthPay += 10
This does essentially nothing, I know, and it's not yet complete. If I add a 'print month' statement it just seems to show that the code just goes up to 12, then starts at 1 again. Any tips/prods in the right direction?
monthly_payment = 10.0
while True:
current_balance = start_balance
for month in range(1, 13):
current_balance = current_balance * (1. + monthly_rate) - monthly_payment
current_balance = round(current_balance, 2)
if current_balance <= 0.0:
break
if current_balance <= 0.0:
print("RESULT")
print("Monthly payment to pay off debt in 1 year: {}".format(int(monthly_payment)))
print("Number of months needed: {}".format(month))
print("Balance: {:0.2f}".format(current_balance))
break
monthly_payment += 10.0

Not getting right output...logic correct

My code is giving right results except for balance=3926. Lowest Payment: 370 whereas it should be 360.The program should print lowest monthly payment for given annual interest rate .Given an initial balance, code should compute the balance at the end of the year. we are trying our initial balance with a monthly payment of $10. If there is a balance remaining at the end of the year, we write code that would reset the balance to the initial balance, increase the payment by $10, and try again (using the same code!) to compute the balance at the end of the year, to see if this new payment value is large enough
annualInterestRate = 0.2
balance = 3926
monthlyinterestrate = annualInterestRate/12.0
remainingBalance = balance
month = 1
total = 0
payment = 10
def CheckMinimumPayment(payment,balance):
"Checking if payment is in correct balance"
while(payment*12 < balance):
payment += 10
return payment
payment = CheckMinimumPayment(payment,balance)
while(month <= 12):
remainingBalance = remainingBalance - payment + (annualInterestRate / 12.0) * (remainingBalance - payment)
month += 1
total += payment
payment = CheckMinimumPayment(payment,total+remainingBalance)
print("Lowest Payment: " + str(payment))
The problem is that you're not re-iterating through the interest loop (what you have as while(month <= 12)) each time you try a new payment. Write that loop into a function, and call it each time you try a new payment. The total owed balance depends on the payment, since a larger payment each month means less interest added each month. Here's what I used:
annualInterestRate = 0.2
init_balance = 3926
monthlyInterestRate = annualInterestRate/12.0
init_payment = 10
def owedBalance(payment,balance):
""" Calculate total owed balance after one year
given an initial balance and montly payment"""
for month in range(12):
balance = (balance - payment) * (monthlyInterestRate + 1)
return payment*12 + balance
def CheckMinimumPayment(payment,balance):
"Checking if payment is in correct balance"
while (payment*12 < owedBalance(payment, balance)):
payment += 10
return payment
min_payment = CheckMinimumPayment(init_payment,init_balance)
print("Lowest Payment: {}".format(min_payment))

Categories

Resources