Python while 循环语法错误

标签 python while-loop

我正在学习 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()' 所以你可以使用

列表中的值 将返回一个 TrueFalse

关于Python while 循环语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38511856/

相关文章:

python - 如何将 Unicode 数据作为西里尔字母符号写入文件?

python - Tensorflow:Cifar-10 模型中的输出节点名称是什么?

python - Swift,如何从 Pandas JSON 文件导入 JSON 文件

python - 重命名从 zipfile 中提取的文件

java - 尝试用循环估计 e^x

java - 在 while 循环中比较 char --- 条件从未满足

python - 如何从 while 循环中获取输入信息?

python - pandas 数据框中 df.loc 第一个参数的范围和单个值之间的差异

javascript - 在我的猜数游戏中遇到 while 循环问题

c - 如何在一个循环中组合序列号和null?