1

The code below works with the number but will not work when I add a dash to the input and I don't know how to make it accept that.

I think the exception works but I don't know if it works properly because I want to error if its a letter.

My question is how do I make it accept the dash with the number in the input and check if the user has put in a letter instead of a number.

def main(day_number,month_number,month_name,date_,month_list,date_1,year,fulldate):              
    day_number = 0                                                                               
    month_number = 0
    month_name = ''                                                                              
    date_ = ''                                                                                  
    month_list = ['January','February','March',                                                  
                  'April','May','June','July',
                  'August','September','October',
                  'November','December']
    date_ = input("Enter a date in the format mm/dd/yyyy: ")
    while True:
        try:
            float(date_)
            date_1= date_.split('/')                                                                      
            month_number = (date_1[0])                                                                
            day_number = date_1[1]
            year = date_1[2]
            month_name = month_list[month_number - 0]                                                   
            fulldate = month_name + ' ' + day_number + ',' + year + '.'                                    
            print(fulldate)
            break
        except ValueError:
            print("""ops it's not a number, please try again""")
            date_ = input("Enter a date in the format mm/dd/yyyy: ")
            break
                                                                                

main("day_number","month_number","month_name","date_","month_list","date_1","year","fulldate")
DojKMGg55
  • 37
  • 3

1 Answers1

0

How about creating a function that takes in a date format and keeps prompting the user till they enter a valid string that matches that date format using datetime.strftime(format) and datetime.strptime(date_string, format):

from datetime import datetime

def get_valid_date_input(prompt, format):
    now = datetime(datetime.today().year, 1, 1)
    prompt_with_example = f"{prompt}, e.g., {now.strftime(format)}:\n"
    date_ = None
    while True:
        try:
            date_ = datetime.strptime(input(prompt_with_example), format)
            break
        except:
            print("Error: Input did not match required format, try again...")
    return date_

def suffix(d):
    # From https://stackoverflow.com/a/5891598/6328256 
    return 'th' if 11 <= d <= 13 else {
        1: 'st',
        2: 'nd',
        3: 'rd'
    }.get(d % 10, 'th')

def main():
    date_format = "%m/%d/%Y"
    date_ = get_valid_date_input(f"Enter a date in the format {date_format}",
                                 date_format)
    print(f"You entered a valid date: {date_.date()}")
    full_month, day_num, year = date_.strftime("%B"), date_.day, date_.year
    print(f"{full_month} {day_num}{suffix(day_num)}, {year}")

if __name__ == '__main__':
    main()

Example Usage:

Enter a date in the format %m/%d/%Y, e.g., 01/01/2020:
11/26/20
Error: Input did not match required format, try again...
Enter a date in the format %m/%d/%Y, e.g., 01/01/2020:
26/11/2020
Error: Input did not match required format, try again...
Enter a date in the format %m/%d/%Y, e.g., 01/01/2020:
11/26/2020
You entered a valid date: 2020-11-26
November 26th, 2020
Sash Sinha
  • 18,743
  • 3
  • 23
  • 40
  • 1
    Thank you so much ! I'm trying to get my head around assignments from school. im trying to take those and then play around with them and add new things. Its just sometimes I hit a brick wall and don't know what's wrong. Thank you so much for this. I will learn from it. Thank you again. – DojKMGg55 Nov 26 '20 at 18:48
  • No problem, I didn't have a `get_valid_date_input` function yet so I needed to write one anyway (I have this `get_int_input` that I have been incorporating into a lot of my answers to tangentially related questions that I've noticed increase my chances for the accept/+25 from the OP (you in this case). Who cares when you get rekt on the stock market when you got StackOverflow rep, am I right XD. – Sash Sinha Nov 26 '20 at 19:08