Home > Net >  new to coding, need if statement help on my own little code I made
new to coding, need if statement help on my own little code I made

Time:10-06

I want to receive how many years/months/weeks/days in total of the number, I want the output to say 732 is 2 years, 0 months, 0 weeks, 2 days but I would receive "it has been: 2 Years , 24 Months , 105 Weeks , 732 Days Since Variable inputted"

*##variables / user input*

days = int(input("Enter Number of Days: "))
weeks = days / 7
months = days / 30.4
years = days / 365

*#if conditions here*

if days >= 7:
    weeks = weeks   1
elif weeks >= 4:
    months = months   1

elif months >= 12:
    years = years   1





*##print command for output*

print("it has been: ", int(years), "Years", ",", int(months)
      , "Months", ",", int(weeks), "Weeks", ",", int(days), "Days","Since Variable inputted")

I know what I'm doing wrong just I don't know the solution for it :D thank you for any informative answers

CodePudding user response:

There are a lot of ways of going about solving this type of problem. Here is one solution that uses divmod.

days = int(input("Enter Number of Days: "))
years, days = divmod(days, 365)
months, days = divmod(days, 30)
weeks, days = divmod(days, 7)

print(f"It has been: {years} years, {months} months, {weeks}, weeks, {days} days,"
        " since the inputted variable.")

divmod divides two numbers and gives back the quotient and remainder. In the code above we divide the number of days by 365, store the quotient as the number of years, and store the remainder as the number of days — overwriting whatever was previously stored in the days variable with the amount of leftover days. This process is then repeated to calculate months and weeks.

CodePudding user response:

You don't really need any if statements here. This is a more mathematical solution than the one above:

days = int(input("Enter Number of Days: "))
years = days // 365
months = (days - 365 * years) // 30.4
weeks = (days - (365 * years   30.4 * months))//7
days = days - (365 * years   30.4 * months   7 * weeks)
print("it has been: ", int(years), "Years", ",", int(months), "Months", ",", int(weeks), "Weeks", ",", int(days), "Days","Since Variable inputted")

It's just recurring subtraction/division.

Also, when dealing with more complicated projects, it can be useful to explain what you've done to try to fix it, your approach, exactly what you want, and since you said you knew what you were doing wrong, you are expected to say that if you have any information.

CodePudding user response:

I would recommend choosing HostingUtilities's solution over OnMyTerm's solution because that solution has much cleaner code

  • Related