Как добавить проценты на баланс банковского счета раз в месяц? - PullRequest
0 голосов
/ 14 октября 2018

Мне нужно создать класс банковского счета, который имеет такие функции, как: депозит, вывод, получение баланса;все эти вещи для начинающих.Все очень просто и я закончил это без проблем.Тем не менее, есть функция, которая называется Interest, которая принимает интереса, где у меня много проблем.Для пояснения, эта функция должна добавлять проценты по запросу пользователя только один раз в месяц к балансу банковского счета.Допустим, я решил добавить 5% на сегодняшнюю дату (13 октября) к своему балансу.Функция будет выполняться и выплюнет мой новый баланс.Скажем, я хочу добавить 10% к проценту на следующий день (14 октября), функция не будет выполняться и выдаст что-то вроде «Невозможно добавить проценты до 1 ноября», что является первым в следующем месяце.1 ноября, если бы я попытался добавить 10%, я бы преуспел, а затем, если бы 2 ноября я попытался снова добавить проценты, он сказал бы: «Невозможно добавить проценты до 1 декабря» и так далее, и так далее.Мне очень тяжело с этим.Ниже приведен код, который я написал, однако он не только будет выполняться всегда, потому что дата всегда будет впереди на месяц, но также будет всегда добавлять интерес к балансу.

Вот что у меня так далеко, но это беспорядок.У кого-нибудь есть какие-либо советы о том, что мне следует делать?Я знаю, что это не внутри функции, как это должно быть в задании, но я подумал, что сначала выясню основную картину программы, а потом буду беспокоиться о ее включении в остальную часть моего класса.

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.")

1 Ответ

0 голосов
/ 14 октября 2018

Я уже закончил, как это сделать.

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")
...