简体   繁体   中英

Python while loop Syntax Error

I am learning Python and while working on a simple while loop I get a syntax error but cannot figure out why. Below is my code and the error I get

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)

I am using NetBeans 8.1 to run these. Below is the error I see after I type in Product 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'

in 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)

in 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

this is because lists don't have the attribute '.get()' so you can use

value in list that will return a True or False value

Use raw_input instead of input . Python evaluates input as pure python code.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM