Q:

Find the day of the week for a given date in the past or future in Python

belongs to collection: Python basic programs

0

In this problem, a particular date will be provided by the user which may be from the past or future and we have to find the weekday. To this, we will use the calendar module which provides us various functions to solve the problem related to date, month and year. Before going to find the weekday of a given particular date, we have to check whether the given date is valid or not. If the given date is not valid then we will get some error. So, to overcome this type of error we will use the try-except statement.

Syntax of try-except statement:

    try:
        #statement 
    except error_types:
        #statement

Algorithm to solve this problem:

  1. Import calendar module in the program.
  2. Take a date from the user in the form of date(d) - month(m) -year(y).
  3. Check the given date is valid or not.
    1. If the date is valid then execute the next statement.
    2. If date is invalid then show ‘you have entered an invalid date' to the user.
  4. Print the weekday of the given date.

Let's start writing the Python program by the implementation of the above algorithm.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Code:

# importing the module
import calendar

d,m,y=map(int,input('Enter the value of date,month and year: ').split())

a=['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']

try:
    s=calendar.weekday(y,m,d)
    print('Weekday:',a[s])
except ValueError:
    print('You have entered an invalid date.')

Output

RUN 1:
Enter the value of date, month and year: 28 10 2019
Weekday: Monday

RUN 2:
Enter the value of date, month and year: 32 10 2019
You have entered an invalid date.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python basic programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Find the number of integers from 1 to n which cont... >>
<< Program to find the x-intercept and y-intercept of...