Home > OS >  Finding the values of avg and total month/rainfall, in Python
Finding the values of avg and total month/rainfall, in Python

Time:10-07

so my issue with this one it is the assemble the datetime function with a new class made by my own, which it should give the year and the month, like on the images, to store the rainfall data. I'm new to this language, so if I can get any suggestions or paths to start on, I would appreciate that.

Also, this is the code that I tried so far, like I said, I don't know on how to structure it(I put the value of 4 for the range of 0-4 for the random.randit):

from random import randint
class datetime:
    def __init__(self, month_name, rainfall_year, value=4): 
        self.month = month_name
        self.year= rainfall_year
        self.value = value

Expected output:

--------------
June (2022) = 1
May (2022) = 2
April (2022) = 3
March (2022) = 1
February (2022) = 3
January (2022) = 2
December (2021) = 0
November (2021) = 4
October (2021) = 4
September (2021) = 0 
August (2021) = 1
July (2021) = 2
-----------------------
Total rainfall: 23
Average rainfall 1.91

Thank you and any constructive opinions or suggestions are accepted as well to keep learning this path, thank you for your consideration.

CodePudding user response:

This looks quite good so far. Don't declare a new class with a name datetime which is an existing entity. You could pass a date object as a constructor argument if you wanted to incorporate it in the implementation like so

from random import randint
from datetime import date


class RainData():
    def __init__(self, rain_date: date, value: int):
        self.rain_date = rain_date
        self.value = value


rd = RainData(rain_date=date(2022, 10, 1), value=randint(0, 4))
print(f"{rd.rain_date.strftime('%B (%Y)')} = {rd.value}")
# Output: October (2022) = 2

To generate data on all 12 months you'd do the following in place of the last two lines here. It loops over numbers from 1 to 12 and adds a RainData entry to a list called year_data and prints it.

year_data = [RainData(rain_date=date(2022, m, 1), value=randint(0, 4)) for m in range(1, 13)]
[print(f"{rd.rain_date.strftime('%B (%Y)')} = {rd.value}") for rd in year_data]

Simpler way to achieve the same outcome looks like this

year_data = []
for month in range(1, 13):
    rd = RainData(rain_date=date(2022, month, 1), value=randint(0, 4))
    year_data.append(rd)
    print(f"{rd.rain_date.strftime('%B (%Y)')} = {rd.value}")

As a side note, if you'd want to extend another class, e.g. datetime you would use syntax like

class RainData(datetime):

which gives you full features of datetime class but with the option of adding your own content. Reference here https://docs.python.org/3/tutorial/classes.html#inheritance

I just don't see it making much sense in your currently described requirements.

  • Related