我正在学习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'
答案 0 :(得分:4)
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
这是因为列表没有属性&#39; .get()&#39;所以你可以使用
value in list
这将返回True
或False
值
答案 1 :(得分:1)
使用raw_input
代替input
。 Python将input
评估为纯Python代码。
quote = raw_input("What services are you interesting in? (Press X to quit)")