[Tutor] looping - beginner question

Alan Gauld alan.gauld at yahoo.co.uk
Thu Mar 2 10:06:28 EST 2017

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:
       break  #exit loop and avoid 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 ("Sorry....)

Alan G
Author of the Learn to Program web site
Follow my photo-blog on Flickr at:

More information about the Tutor mailing list