Tip:
Highlight text to annotate it
X
Okay, here's 1 version of this function.
First, what we do is we take the month string from the user, if it's there,
if it's a nonempty string.
I capitalize it because the list I include before of all of the months
has the days capitalized,
and if that capitalized month is in that list, return that value.
So let's try a couple versions of this.
Valid_month('january'), and we run this.
We see it prints January.
Let's try 'july'. I run this, and it prints July.
Everything is formatted nicely, and all is well.
Okay, now let's try answering some junk in here.
Okay, we run this, and it returns nothing.
What happens if I answer in nothing?
We get nothing. Okay, so this seems to be working.
Now what if we wanted to make this a little bit more user friendly,
so the user doesn't have to type in a complete month and spell it correctly.
Here's the change I would probably make.
At the top of this file, we have a list of months.
What I'm going to do is, I'm going to build a dictionary--a mapping of just the first 3 letters
of the month name to the month name itself,
so we're only going to match on the first 3 letters of what the user enters.
Okay, so I've added this dictionary, and for m in months,
which is our list from above of the month names,
we're going to make a mapping of the first 3 letters of that month--
that's what this m[:3] is--lowercase using the lower() function to the month name itself.
If I were to print that out, it looks like this down here--
'mar' to March, 'feb' to February, 'aug' to August--you get the point.
Now this isn't in any particular order because in Python, dictionaries aren't ordered.
Now let's update the main function here to use this new dictionary.
Okay, so now I've made the changes. We still say, if month.
Now I'm making a new variable called short_month,
which just equals the first 3 letters of whatever the user typed in, lowercased--
so first 3 letters, lowercase.
Then I use the GET function on a Python dictionary to see if those first 3 letters
the user typed in is in that mapping, and if it is, we return the value from that mapping.
That's what the GET function does.
It says, if our key is in the mapping, return the value. Otherwise, return none.
We're going to return either that value or none.
Let's try this out together.
So print valid_months.
Okay, so I run this function on 'january', like we did before, and it prints out January
with a capital J. That's the behavior we had before.
Let's try something a little bit different. What if I type in just 'feb'?
If I run this, we get February with a capital F, so now our date field in our form
will be able to accept a wider variety of things.
If you're like me, and you can never spell February correctly--I'll misspell this,
and I hit run, we still get February nicely.
This is nice, so I can type in any sorts of junk,
and if the first 3 letters match a month, we can assume the user was probably
on the right track. Okay? See--December.