iwheeler
iwheeler

Reputation: 3

if statement string checking with casefold python

This is a simple program to check how old you are but I don't understand why it's not working. I know it's something to do with the .casefold(), because when I take it out it works, but I don't want to have to add an if statement for every single capitalization possibility for each month. What am I doing wrong?

user_birth_year = input('What year were you born? ')
print('\n')
user_birth_month = input('What month were you born? ')

if user_birth_month.casefold() == ['April', 'January']:
    print(2020 - int(user_birth_year))

Upvotes: 0

Views: 468

Answers (3)

Binh
Binh

Reputation: 1173

Your if statement has a problem. It should be in not ==. And one more thing, they usually lower case all strings when comparing them, not capitalize them

if user_birth_month.lower() in ['april', 'january']:

Upvotes: 0

Diogenis Siganos
Diogenis Siganos

Reputation: 797

You should use the capitalize() method instead:

user_birth_year = input('What year were you born? ')
print('\n')
user_birth_month = input('What month were you born? ')

if user_birth_month.capitalize() in ['April', 'January']:
    print(2020 - int(user_birth_year))

Upvotes: 0

Adam Smith
Adam Smith

Reputation: 54163

The canonical way to do this is to casefold both strings

if user_input.casefold() == "April".casefold():
    # do a thing

If you're checking multiple, then fold the whole list

if user_input.casefold() in [month.casefold() for month in list_of_months]:
    # do a thing

Upvotes: 1

Related Questions