Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
268 views
in Technique[技术] by (71.8m points)

python - How to make months not exceed 12

I am working on a small project where the code will approximately calculate what the date will be when they are one billion seconds old. I am done but I have a problem. If a user enters "5" as month or higher, then the month will exceed 12. Same for the date, it will go over 31 days if the user enters "24" or higher. How do I make it so that it will not go above "12" for months and "31" for days. Only problem is the month and the day, the year is working fine. Thanks!

When running the code, a sample you can use is, "10" as month, "24" as day and "2020" for year.

Code:

month = int(input("What Month Were You Born In: "))
day = int(input("What Day Was It: "))
year = int(input("What Year Was It: "))

sum1 = day + 7
sum2 = month + 8
sum3 = year + 32

print("You will be a billion seconds old approximately around, " + str(sum1) + "/" + str(sum2) + "/" + str(sum3))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

While you could do this using if statements, it's (arguably) cleaner to use the datetime built-in library, which natively handles dates.

import datetime # imports it so it can be used

month = int(input("What Month Were You Born In: ")) #your code
day = int(input("What Day Was It: "))
year = int(input("What Year Was It: "))

born = datetime.datetime(year, month, day)#creates a datetime object which contains a date. Time defaults to midnight.

output = born + datetime.timedelta(seconds = 1000000000)#defines and applies a difference of 1 billion seconds to the date

print(output.strftime("%m/%d/%Y")) #prints month/day/year

If you do want to do it without datetime, you can use this:

month = int(input("What Month Were You Born In: "))
day = int(input("What Day Was It: "))
year = int(input("What Year Was It: "))

sum1 = day + 7
sum2 = month + 8
sum3 = year + 32

if sum1 > 31: # checks if day is too high, and if it is, corrects that and addr 1 to the month to account for that.
    sum1 -= 31
    sum2 += 1
    
if sum2 > 12: #does the same thing for month
    sum2 -= 12
    sum3 += 1
    
print("You will be a billion seconds old approximately around, " + str(sum1) + "/" + str(sum2) + "/" + str(sum3))

Note that this option is less precise than the datetime option, since it doesn't take into account leapyears or various lengths of months.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...