python语法错误30/09/2013

Sup*_*Bob 1 python syntax-error

我的代码在=部分上显示"<= 80"的行返回错误.这是为什么?我该如何解决?

#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)
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激

kar*_*ikr 6

这是无效的:

if number_books >= 51 and <= 80
Run Code Online (Sandbox Code Playgroud)

尝试:

if number_books >= 51 and number_books <= 80
Run Code Online (Sandbox Code Playgroud)

与其他所有事件相同

或者,正如nneonneo提到的那样,

if 51 <= number_books <= 80
Run Code Online (Sandbox Code Playgroud)

此外,您需要在最后以正确的方式返回折扣(这将是您在解决此问题后将遇到的另一个问题).

所以,

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
Run Code Online (Sandbox Code Playgroud)

  • 更好的是,`如果51 <= number_books <= 80` (4认同)

nne*_*neo 6

如果您正在进行范围测试,则可以使用链式比较:

if 51 <= number_books <= 80:
Run Code Online (Sandbox Code Playgroud)

至于为什么会出现语法错误:(andor)运算符的两边必须是完整表达式.由于<= 80不是完整的表达式,因此会出现语法错误.您需要编写number_books >= 51 and number_books <= 80以修复该语法错误.