Home > OS >  New to Python, need help where to put .lower() into my code
New to Python, need help where to put .lower() into my code

Time:07-12

I am unsure where to put ".lower()" into my code below so the user can enter any of the three options without being case-sensitive. For example, they can enter NEW york and it wouldn't give an error because it's not spelled exactly as listed in the code.

while True:
      city = input ("\nWhich city would you like to filter by? New York, Chicago or Washington?\n")
      if city not in ('New York', 'Chicago', 'Washington'):
        print("Error, please choose from one of the options listed")
        continue
      else:
        break

CodePudding user response:

You just need to use the lower() method on a string like this city.lower(). Although you'll get a further problem because your string will be lower case and your cities are title case which would need city.title() to match.

As long as you are consistent with your approach it will be fine as users will type anything from New York to NEW YORK to new york and EveERYThiNG between.

You can read more about the string methods here.

while True:
      city = input ("\nWhich city would you like to filter by? New York, Chicago or Washington?\n")
      if city.title() not in ('New York', 'Chicago', 'Washington'):
        print("Error, please choose from one of the options listed")
        continue
      else:
        break
  • Related