简体   繁体   中英

How to print only once the items in a list (Python 2.7)

I'm a beginner at Python and I've made a code that prints a list of products that the user entered, but whenever I print it, it doesn't break when it reaches the last element...
EDIT: The string is supposed to be with no spaces. ex: Cottage,Cheese,Bacon
Here's my code:

def menu():
    print "1. View products"
def view(products):
    print products
def main():
    str1 = raw_input("")
    products =str1.split(',')
    menu()
    choice = input("")
    while (choice != 0):
        if(choice == 1):
            view(products)
main()

You've got an infinite loop which is why the list keeps getting printed. You need to ask for input more than once otherwise the loop will never end

choice = None
while (choice != 0) and (choice != 1):
    if(choice == 1):
        view(products)
    choice = input("Type 1 to view products, 0 to quit: ")

In this code you only prints list, and while in this case generates infinite loop. In your example products is a list. So why you wouldn't pass it to view function, and then pass it to for loop to print content of products

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