2016-01-29 42 views
-2

https://www.codecademy.com/en/courses/python-beginner-P5YtY/1/6?curriculum_id=4f89dab3d788890003000096如果條件沒有在這是codeacademy

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 

任務之一在此代碼,它提交給codeacedemy返回220代碼時正常工作僅是第一個返回值,但它什麼都沒有檢查我猜?

+2

代碼執行爲'城市==(真或真)' - >'city == true'。你不能做'somevalue == val或val或val或','or'首先被解析/執行並簡化爲一個布爾值true/false。你需要'city ==「Tampa」或city ==「tampa」'例如請閱讀:https://docs.python.org/2/reference/expressions.html第5.15節「運算符優先級」 –

回答

0

你可以做

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

或者

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

字符串的另一個選擇是使用lower方法(如果你想不區分大小寫comparisson)

if city.lower() == "tampa": 
+0

我介紹了你。 – saarrrr

3

您需要確保檢查城市價值的對陣雙方值:

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

否則,Python會將此解釋爲,如果(city == "Tampa") or ("tampa"),其中後者將始終評估爲True

另外,如果你要檢查多個條件在列表中,你可以把值的數組:

tampa = ["Tampa", "tampa"] 
if city in tampa: 
    # do stuff 
0

你不能在同一時間檢查兩個不同值的城市值。

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 
0

您可以使用:

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

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