2013-09-30 49 views
1

我的代碼正在返回一個錯誤,它在= part上顯示「< = 80」。這是爲什麼?我該如何解決它?python語法錯誤30/09/2013

#Procedure to find number of books required 
def number_books(): 
    number_books = int(raw_input("Enter number of books you want to order: ")) 
    price = float(15.99) 
    running_total = number_books * price 
    return number_books,price 

#Procedure to work out discount 
def discount(number_books): 
    if number_books >= 51 and <= 80: 
     discount = running_total/100 * 10 
    elif number_books >= 11 and <=50: 
     discount = running_total/100 * 7.5 
    elif number_books >= 6 and <=10: 
     discount = running_total/100 * 5 
    elif number_books >=1 and <=5: 
     discount = running_total/100 * 1 
    else print "Max number of books available to order is 80. Please re enter number: "   
     return discount 

#Calculating final price 
def calculation(running_total,discount): 
    final_price = running_total - discount 

#Display results 
def display(final_price) 
print "Your order of", number_books, "copies of Computing science for beginners will cost £", final_price 

#Main program 
number_books() 
discount(number_books) 
calculation(running_total,discount) 
display(final_price) 

任何幫助,將不勝感激

+1

請發佈完整的錯誤。 – thegrinner

+0

@thegrinner:語法顯然是錯誤的,並且是一個常見的初學者錯誤。 –

+2

@MartijnPieters我知道,我只是想讓OP習慣於發佈完整的錯誤,所以如果將來有更多的問題,它不會放慢速度。 – thegrinner

回答

6

這是無效的:

if number_books >= 51 and <= 80 

嘗試:

if number_books >= 51 and number_books <= 80 

與所有其他occurances同其

或者, 一個小號nneonneo提到,

if 51 <= number_books <= 80 

此外,您還需要在年底返回的折扣以正確的方式(這將是你會遇到一旦這個問題解決了另一個問題)。

所以,

def discount(number_books): 

    if 51 <= number_books <= 80: 
     discount = running_total/100 * 10 
    elif 11 <= number_books <= 50: 
     discount = running_total/100 * 7.5 
    elif 6 <= number_books <= 10: 
     discount = running_total/100 * 5 
    elif 1 <= number_books <= 5: 
     discount = running_total/100 * 1 

    return discount 


def number_books(): 
    num_books = int(raw_input("Enter number of books you want to order: ")) 
    if numb_books <= 0 or num_books > 80: 
     print "Max number of books available to order is 80, and minimum is 1. Please re enter number: "   
     number_books() 

    price = float(15.99) 
    running_total = num_books * price 
    return number_books,price 
+4

更好的是,如果51 <= number_books <= 80' – nneonneo

6

如果你正在做測試的範圍內,你可以使用一個chained comparison

if 51 <= number_books <= 80: 

至於爲什麼你得到一個語法錯誤:一個and兩側(或or)運算符必須是完整表達式。由於<= 80不是完整的表達式,因此會出現語法錯誤。您需要編寫number_books >= 51 and number_books <= 80來修復該語法錯誤。

+0

您可能想鏈接到文檔。這個功能被稱爲「鏈式比較」。然而,你沒有解釋OP在理解上出錯的地方。 –

+0

謝謝,添加了一個文檔鏈接。 – nneonneo

+0

解釋一下爲什麼他會得到錯誤,因爲國際海事組織,目前這不是他的問題/疑問的正確答案。 – KurzedMetal