Home > Blockchain >  doing a python code and am in need of help in setting up conditions for a string
doing a python code and am in need of help in setting up conditions for a string

Time:06-17

Basically I'm doing a python code in which a full date is input as a string in the format DD-YY-MM and then the day, month and year is output separately. I need to validate the date which is input so the following conditions are met:

  1. the date is not below 1 or over 31
  2. the month is in the range of 1 to 12
  3. the year is not less than 1900
FullDate=input("enter todays date")

D=FullDate[0:2]
M=FullDate[3:5]
Y=FullDate[6:10]

if D>31 and D<1:
    print ("invalid date")
else:
    print("the date is",D)

if M<1 and M>12:
    print("invalid month")
else:
    print("the date is",M)

if Y<1990:
    print ("invalid year")
else:
    print("the year is",Y)

This is what I have tried but since the date is input as a string I cannot use > and < in if conditions and when I do I get the error:

TypeError: '>' not supported between instances of 'str' and 'int'

how do I set up these conditions while also having the input as a string?

CodePudding user response:

You must explicitly cast your string into an int :

import sys
FullDate=input("enter todays date")
D=FullDate[0:2]
M=FullDate[3:5]
Y=FullDate[6:10]

if int(D)>31 or int(D)<1:
    sys.exit("invalid day")
else:
    print("the day is",D)

if int(M)<1 or int(M)>12:
    sys.exit("invalid month")
else:
    print("the month is",M)

if int(Y)<1990:
    sys.exit("invalid year")
else:
    print("the year is",Y)
  • Related