计算特定月份收到的总罚款

时间:2019-11-13 12:37:08

标签: python

我想计算特定月份收到的总罚款(将数据保存在列表中),但我不知道该怎么做。谁能帮忙吗?

bookcode = str(input('Enter Book Code To Return: ')) 
day = int(input('Enter Days Borrowed:'))

if(0 <= day <= 5):
        print('You have returned your book successfully =)') 
else:
    penalty = (day-5) * 1
    print('You have to pay RM%.2f ,%penalty)


print('\nYou have to pay RM','%.2f'%penalty)

1 个答案:

答案 0 :(得分:0)

您已经提供了代码,但没有提供用例(它是否在每个月末运行?每次有人想归还一本书吗?等等)。

暂时,我们假设每次有人要归还一本书时我们都在运行此代码。

所以要分解它:

  1. 您的应用程序需要知道我们当前的日期
  2. 它需要加载从某种形式的持久性存储(数据库或文件)中提交的先前数据。

要解决约会问题,我们可以使用datetime library that's part of pythons standard library

我们将其导入并调用datetime.datetime.now()方法,该方法为我们提供了一个datetime对象,其中包含当前日期和时间。 然后,我们可以使用上述对象来计算出我们当前所在的月份。

import datetime

now = datetime.datetime.now()
print(now.month)

请注意,这将返回一个整数。要获取月份名称,我们可以使用日历API(也可以在标准库中找到)

import datetime
import calendar

now = datetime.datetime.now()
print(calendar.month_name[now.month])

现在有一个月了,我们可以将其数据附加到字典中。

要跟踪以前输入过什么数据,我们需要一些持久性存储。最简单的方法是创建文件并以json格式向其中写入数据。

从(再次)从标准库导入json开始。然后创建一个字典,将其写入文件。

import os

# our data file name
data_file_name = 'data.json'

# check if there is an existing file
data_present = os.path.isfile(data_file_name)

# if present, open the file in read only mode and fetch it's contents.
if data_present:
    with open(data_file_name, 'r') as _f:
        json_data = _f.read()
else:  # data file not found, create one and a dummy json object.
    json_data = json.dumps({calendar.month_name[i]: [] for i in range(1,13)})
    with open(data_file_name, 'w+') as _f:
        _f.write(json_data)

# try parsing json data
try:
    data = json.loads(json_data)
except ValueError:
    print('Failed to decode json data')

现在我们缺少了一些片段,我们可以将该代码添加到您的应用程序中。

import datetime
import calendar
import json
import os

now = datetime.datetime.now()  # Get current date and time
month = calendar.month_name[now.month]  # current month

# Read data from the json file.

# our data file name
data_file_name = "data.json"

# check if there is an existing file
data_present = os.path.isfile(data_file_name)

# if present, open the file in read only mode and fetch it's contents.
if data_present:
    with open(data_file_name, "r") as _f:
        json_data = _f.read()
else:  # data file not found, create one and a dummy json object.
    json_data = json.dumps({calendar.month_name[i]: [] for i in range(1, 13)})
    with open(data_file_name, "w+") as _f:
        _f.write(json_data)

# try parsing json data
try:
    data = json.loads(json_data)
except ValueError:
    print("Failed to decode json data")


bookcode = str(input("Enter Book Code To Return: "))
day = int(input("Enter Days Borrowed: "))
penalty = None  # Make sure we have a penalty variable

if 0 <= day <= 5:
    print("You have returned your book successfully =)")
else:
    penalty = (day - 5) * 1
    print(f"RM {penalty:2f} added to {month} penalty")

# Now add the additional data to our data.json file.
if penalty:  # Resolves to true if it's not None or False
    with open(data_file_name, "w") as _f:
        data[month].append(penalty)  # Add penalty to the month in our data.
        _f.write(json.dumps(data))  # Write our new data to file in json format

# Show user overall penalty
overall_month_penalty = sum(data[month])

print(f"\nYou have to pay RM {overall_month_penalty}")

请注意,这仅适用于每年。新年伊始,您必须删除data.json

参考文献:

PS:您有错字:print('You have to pay RM%.2f ,%penalty)应该是print('You have to pay RM%.2f' %penalty)(添加'并删除,