On 03/02/2017 08:06 AM, Alan Gauld via Tutor wrote: > On 02/03/17 13:42, Rafael Knuth wrote: > >> bar = ["beer", "coke", "wine"] >> >> customer_order = input("What would you like to drink, dear guest? ") >> >> for drink in bar: >> if customer_order != drink: >> print ("Sorry, we don't serve %s." % customer_order) >> else: >> print ("Sure, your %s will be served in a minute!" % customer_order) >> >> What I want the program to do is to "silently" loop through the list > > So you only want the sorry... message if the loop completes without > finding a drink. That means you need to put that print statement after > the loop. Python includes a feature for that - a for/else construct. > > for drink in bar: > if drink == customer_order: > print(Sure...) > break #exit loop and avoid else > else: > # only if the loop completes normally > > However, there is another way to do this that doesn't > use an explicit loop: the 'in' operator > > if customer_order in bar: > print("sure....) > else: > print ("Sorry....)
To follow on to what Alan said, you don't need to loop over a list (or tuple, or dictionary, or other "iterable") to find out if it contains an item. You can just test membership directly. _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor