What is the output of the following code?
from datetime import date first_date = date(2014, 7, 2) last_date = date(2014, 7, 11) n = last_date - first_date print(n.days)
from datetime import date first_date = date(2014, 7, 2) last_date = date(2014, 7, 11) n = last_date - first_date print(n.days)
from datetime import date
first_date = date(2014, 7, 2)
last_date = date(2014, 7, 11)
n = last_date - first_date
print(n.days)
9
9 days
The code imports the date class from the datetime module. It then creates two date objects, first_date and last_date, which are set to July 2nd, 2014 and July 11th, 2014 respectively. The variable n is assigned the value of the difference between last_date and first_date, which is calculated using the subtraction operator. The program then prints the number of days between the two dates by accessing the days attribute of the timedelta object returned by the subtraction operation. The output will be 9 days.
First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.
Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.