簡體   English   中英

Python while循環語法錯誤

[英]Python while loop Syntax Error

我正在學習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()',所以您可以使用

value in list中的value in listvalue in list將返回TrueFalse

使用raw_input代替input Python將input評估為純python代碼。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM