0

I am slightly new to python still. What the end goal is to use the following code to search the list and print out each grb.name in the list. The thing is I am wanting to use user input and I am running into the problem that if the user enters a date that isn't in the list it needs to automatically correct it by adding one until it reaches the next grb_date and then execute the code. This goes for both the start_date and end_date.

for i, grb in enumerate(results): #prolem with multiple grb's in 1 day
    try:
        grb_date = (re.sub('[A-Z]','',grb.name))
        end_results = [i, grb_date]
        data[str(grb_date)] = i  # this is the important bit
#            print (end_results)
    except:    
        pass

#start_date = (input('What is the start date you want: '))  
#end_date = (input('What is the end date you want: '))   

while 1:
    start_date = input('Please choose a start date: ')
    end_date = input('Please choose an end date now: ')
    try: 
        while data[start_date] <= data[end_date]:
                print (results[data[start_date]].name)
                data[start_date] += 1

    except KeyError:
        while data[start_date] not in end_results:
            data[start_date] += 1
        x = data[data[start_date]]
        print ('Try using this date instead: %d'), x

This is what I currently have. I keep getting KeyError '111111' (or whatever the start_date was if it was wrong).

2 Answers 2

1

You get the error because the incorrect start_date does not exist as a key in dict data.

Change your last while loop to -

while data.get('start_date', None) not in end_results:
    ....
Sign up to request clarification or add additional context in comments.

Comments

0

This should be a bit obvious

try: 
    while data[start_date] <= data[end_date]:
            print (results[data[start_date]].name)
            data[start_date] += 1

And ...

except KeyError:
    while data[start_date] not in end_results:

The same key, start_date, is occuring in your handling of the key error (causes by the same key). Although EFAP is great, do it properly.

You need to set start_date into data.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.