Unit 3 Sections 14-15 Homework
Here are the instructions for the homework for sections 14-15.
Create a program that asks the user for a day and then gives them a distance in days between that day and another random day in the year. We have provided you with a possible starter, but you are welcome to change it up if you would like.
from datetime import date
import random
days_dictionary = {
1: 31,
2: 28,
3: 31,
4: 30,
5: 31,
6: 30,
7: 31,
8: 31,
9: 30,
10: 31,
11: 30,
12: 31,
}
print("Input a day")
day = int(input("Input a day"))
print(str(day))
print("Input a day")
month = int(input("Input a month"))
print(str(month))
print("Input a year")
year = int(input("Input a year"))
print(str(year))
print("User day: " + str(month) + "/" + str(day) + "/" + str(year))
randommonth = random.randint(1,12)
randomday1 = days_dictionary.get(randommonth)
randomday = random.randint(0,randomday1)
print("Random day: " + str(randommonth) + "/" + str(randomday) + "/" + str(year))
def ndays(month,day):
num = 0
for i in range (1,month):
num += (days_dictionary.get(i))
num += int(day)
return(num)
num1 = ndays(month,day)
num2 = ndays(randommonth,randomday)
math = abs(num1 - num2)
print("The number of days between the given range of dates is: " + str(diff))
# expected output shown below (or something similar)
code explained: The code imports the datetime and random modules, which are used to create date objects and generate random numbers. The code then creates a dictionary that maps each month to the number of days in that month. This is used later to calculate the number of days between two dates. The code then asks the user for a day, month, and year, and then uses the datetime.date() function to create a date object from these values. The code generates a random day and month using the random.randint() function, and then creates a date object from these values and the user-specified year. The code defines a ndays() function that takes a month and day as arguments, and returns the number of days that have passed since the beginning of the year up to the given date. The code calls the ndays() function twice, once for the user-specified date and once for the random date, and assigns the result to the num1 and num2 variables. The code calculates the difference between num1 and num2 using the abs() function, which returns the absolute value of the difference, and assigns the result to the math variable. The code prints the value of the math variable, which is the number of days between the user-specified date and the random date.