2016-07-21 131 views
1

我正在学习Python,并在一个简单的while循环上工作时出现语法错误,但找不到原因。下面是我的代码和我得到的错误Python while循环语法错误

products = ['Product 1', 'Product 2', 'Product 3'] 
quote_items = [] 
quote = input("What services are you interesting in? (Press X to quit)") 
while (quote.upper() != 'X'): 
    product_found = products.get(quote) 
    if product_found: 
     quote_items.append(quote) 
    else: 
     print("No such product") 
    quote = input("Anything Else?") 
print(quote_items) 

我正在使用NetBeans 8.1来运行这些。下面是我看到的错误后,我在产品类型1:

What servese are you interesting in? (Press X to quit)Product 1 
Traceback (most recent call last): 
File "\\NetBeansProjects\\while_loop.py", line 3, in <module> 
quote = input("What services are you interesting in? (Press X to quit)") 
File "<string>", line 1 
Product 1 
SyntaxError: no viable alternative at input '1' 
+3

您是否正在Python 2上运行为Python 3编写的代码? – user2357112

+0

我想我正在运行3.有没有办法检查? – user3088202

+2

在附注中,列表没有任何'get'方法:'products.get(quote)'会引发错误 –

回答

4

的Python 3

products = ['Product 1', 'Product 2', 'Product 3'] 
quote_items = [] 
quote = input("What services are you interesting in? (Press X to quit)") 
while (quote.upper() != 'X'): 
    product_found = quote in products 
    if product_found: 
     quote_items.append(quote) 
    else: 
     print("No such product") 
    quote = input("Anything Else?") 
print(quote_items) 

的Python 2

products = ['Product 1', 'Product 2', 'Product 3'] 
quote_items = [] 
quote = raw_input("What services are you interesting in? (Press X to quit)") 
while (quote.upper() != 'X'): 
    product_found = quote in products 
    if product_found: 
     quote_items.append(quote) 
    else: 
     print "No such product" 
    quote = raw_input("Anything Else?") 
print quote_items 

这是因为列表没有属性 '获得()' 这样你就可以使用

value in list 将返回一个TrueFalse

1

使用raw_input而不是input。 Python将input评估为纯Python代码。

quote = raw_input("What services are you interesting in? (Press X to quit)") 
+0

如果他使用Python 3,则不需要。 –

+0

@JohnGordon显然他不是。 – chepner

+0

@chepner如果他真的在使用Python 2,那么我会期望从“产品1”的用户输入中产生一个不同的错误。 –