2015-04-22 180 views
0
sales = 1000 

#def commissionRate(): 

if (sales < 10000): 
    print("da") 
else: 
    if (sales <= 10000 and >= 15000): 
     print("ea") 

if if (sales <= 10000 and >= 15000): line上的語法錯誤。特別是在等號。爲什麼我得到語法錯誤?

+0

是您的實際縮進? –

回答

6

你需要比較sales對第二個條件也:

In [326]: 

sales = 1000 
​ 
#def commissionRate(): 
​ 
​ 
if (sales < 10000): 
    print("da") 
else: 
    if (sales <= 10000 and sales >= 15000): 
     print("ea") 
da 

你需要這個:

if (sales <= 10000 and sales >= 15000): 
         ^^^^ sales here 

另外,你不需要括號周圍if條件()

if sales <= 10000 and sales >= 15000: 

正常工作

您可以將其改寫爲更加緊湊:

In [328]: 

sales = 1000 
​ 
if sales < 10000: 
    print("da") 
else: 
    if 10000 <= sales <= 15000: 
     print("ea") 
da 

所以if 10000 <= sales <= 15000:作品也感謝@Donkey香港

另外(感謝@pjz)和無關的代碼是邏輯上的銷售不能都小於10000並且大於15000.

因此即使沒有語法錯誤,條件也不會是True

你想if sales > 10000 and sales <= 15000:if 10000 <= sales <= 15000:這可能更清楚你

只是對if 10000 <= sales <= 15000:語法擴展(感謝@will您的建議),在蟒蛇一個可以執行數學比較lower_limit < x < upper_limit還解釋here是不是更自然通常是if x > lower_limit and x < upper_limit:

這樣的比較來進行鏈接,從文檔:

Formally, if a , b , c , ..., y , z are expressions and op1 , op2 , ..., opN are comparison operators, then a op1 b op2 c ... y opN z is equivalent to a op1 b and b op2 c and ... y opN z , except that each expression is evaluated at most once.

+4

值得一提的是,如果(10000 <=銷售<= 15000)'也許? – miradulo

+0

@DonkeyKong好點,也編輯了這個例子 – EdChum

+1

你也應該指出他的邏輯錯誤:銷售永遠不能小於10k和大於15k。 – pjz

2

關於語法:

if (sales <= 10000 and >= 15000):應該if (sales <= 10000 and sales >= 15000):

關於邏輯:

銷售情況從來沒有samller臨屋區n或等於10,000且大於或等於15,000

if (10000 <= sales <= 15000):

相關問題