Search code examples
pythonvalueerror

Value Error for code that converts numerical values into DOB


I tried to create a program that asks for users to give their DOB in a numerical format. It was working until a line where I specified that if the day value they input was over 31 then it was invalid. I'm receiving this error: ValueError: invalid literal for int() with base 10: (day value)

My code looks like this:

uy = input("Enter your birth year: ")
um = input("Enter the number of your birth month (1-12): ")
mn = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]

if um == "1":
    mn = "January"
elif um == "2":
    mn = "February"
elif um == "3":
    mn = "March"
elif um == "4":
    mn = "April"
elif um == "5":
    mn = "May"
elif um == "6":
    mn = "June"
elif um == "7":
    mn = "July"
elif um == "8":
    mn = "August"
elif um == "9":
    mn = "September"
elif um == "10":
    mn = "October"
elif um == "11":
    mn = "November"
elif um == "12":
    mn = "December"

day = input("please enter the day number of the date (1-31): ")

if day == '1' or day == '21' or day == '31':
    day = day + "st"
elif day == '2' or day == '22':
    day = day + "nd"
elif day == '3' or day == '23':
    day = day + "rd"
else:
    day = day + "th"

if mn == "February" and int(day) <= 28:
    vd = True
elif (mn == "April" or mn == "June" or mn == "September" or mn == "November") and int(day) <= 30:
    vd = True
elif mn in ["January", "March", "May", "July", "August", "October", "December"] and int(day) <= 31:
    vd = True
else:
    vd = False

if vd:
    print(f"Your date of birth is the {day} {mn} {uy}")
else:
    print("The data entered was not valid, please try again.")

I'm still a beginner and I can't figure what I've done wrong. Thanks for any help.


Solution

  • Your problem is that you modify your day variable adding it "nd","st",etc. So the day variable is now a number and letters. The programm doesn't know how to covert to int and crashes. I suggest using another variable like day_modified to store that value of 31st.