[Tutor] Coding

Alan Gauld alan.gauld at btinternet.com
Mon Dec 8 02:47:39 CET 2014


On 07/12/14 15:27, Awais Idris wrote:

> found some coding online and I have changed some of it, but it still
> doesn't work. I think theres a problem with the loops and a few other
> things that I cant put my finger on.

First, Please post the code into your message rather than as an 
attachment. Its easier to reply to that way...

Second, you don't have any loops. Loops are where the code
repeats itself until some condition is true. You have
selections not loops.

With those nitpicks out of the way...

 > Drinks = {'Coke','Sprite','Water'}
 > Snacks = {'Hershey', 'Snickers','Twix','Maltesers','Crisps'}
 >
 > FirstChoice = input ("Enter the item of your choice: ")
 > if FirstChoice == 'Coke' or 'Pepsi' or 'Water':
 >    print ("That will be a total of £",drinks)

The or statements don't do what you think.

Python sees it like:

if FirstChoice == ('Coke' or 'Pepsi' or 'Water'):

So evaluates the bit in parens first which results in a boolean value of 
True.

So it sees the 'if' part as:

if FirstChoice == True:

Which it isn't, so the if never prints.

 > elif FirstChoice == 'Hershey' or 'Snickers' or 'Twix' or 'Maltesers'

Same here...

 > else:
 >    print ("****er")

So this is what gets printed  each time...

 > SecondChoice = input ("Would you like anything else? Yes/No ")
 > if SecondChoice == "Yes" or "yes":

And again...

     if SecondChoice == (Drinks):
         print ("That will be a total of £",drinks)
     elif SecondChoice == (Snacks):
         print ("That will be a total of £",snacks)

Not sure what you think happens here but again they will both be False 
so won't print.

I suspect you need to look at the 'in' operator.
Then you can do things like:

if FirstChoice in Drinks:

and so on.


HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list