-2

https://www.codecademy.com/en/courses/python-beginner-P5YtY/1/6?curriculum_id=4f89dab3d788890003000096

def plane_ride_cost(city):

  if city== "Tampa" or "tampa":
      return 220 
  elif city== "Charlotte" or "charlotte":
      return 183
  elif city== "Pittsburgh" or "pittsburgh":
      return 222
  elif city== "Los Angeles" or "los angeles":
      return 474

In this code, which when submitted to codeacedemy it returns 220 only that is the first return value, except it nothing is checked I guess?

saarrrr
  • 2,754
  • 1
  • 16
  • 26
  • 2
    the code executes as `city == (true or true)` -> `city == true`. you can't do `somevalue == val Or val or val or`, the `or` are parsed/executed first and reduced to a single boolean true/false. you need `city == "Tampa" or city == "tampa"` e.g. read this: https://docs.python.org/2/reference/expressions.html section 5.15 "operator precedence" – Marc B Jan 29 '16 at 20:07

4 Answers4

3

You need to make sure to check the value of city against both values:

i.e.

if city == "Tampa" or city == "tampa":
    # do stuff

Otherwise, Python will interpret this as if (city == "Tampa") or ("tampa"), the latter of which will always evaluate to True

Alternatively, if you want to check multiple conditions in a list, you can put the values in an array:

tampa = ["Tampa", "tampa"]
if city in tampa:
    # do stuff
Alex Alifimoff
  • 1,850
  • 2
  • 17
  • 34
0

You cannot check the value of city against two different values at the same time like that.

def plane_ride_cost(city):
  if city == "Tampa" or city == "tampa":
      return 220 
  elif city == "Charlotte" or city == "charlotte":
      return 183
  elif city == "Pittsburgh" or city == "pittsburgh":
      return 222
  elif city == "Los Angeles" or city == "los angeles":
      return 474

OR

def plane_ride_cost(city):
  if city in ["Tampa","tampa"]:
      return 220 
  elif city in ["Charlotte","charlotte"]:
      return 183
  elif city in ["Pittsburgh","pittsburgh"]:
      return 222
  elif city in ["Los Angeles","los angeles"]:
      return 474
saarrrr
  • 2,754
  • 1
  • 16
  • 26
0

You can use:

if city in ["Tampa", "tampa"]:
    #code

or

if city.lower() == "tampa":
    #code
0

You could do

if city == "Tampa" or city == "tampa":

Or

if city in ("Tampa", "tampa"):

Another option for strings is use lower method (If you want a case-insensitive comparisson)

if city.lower() == "tampa":
Mr. E
  • 2,070
  • 11
  • 23