Skip to main content
 首页 » 编程设计

Python while 循环语法错误

2025年05月04日29jiqing9006

我正在学习 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' 

请您参考如下方法:

在 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 

这是因为列表没有属性 '.get()' 所以你可以使用

列表中的值 将返回一个 True 或 False 值