2016-07-21 130 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」的用戶輸入中產生一個不同的錯誤。 –