[Tutor] Refining Code

Alan Gauld alan.gauld at btinternet.com
Fri Apr 11 02:21:06 CEST 2014


On 10/04/14 23:26, Saba Usmani wrote:
> My task is :
> A food vending machine accepts 10p, 20p, 50p and £1 coins....
> */I have designed the following code, but would like to know how to make
> it more efficient without making it too complex as I am a beginner

Have you covered functions yet?
If so you can use functions to remove a lot of duplication from the code 
which will make it clearer. But if you haven't covered functions then 
what you have is not too bad.

Thee is one bad habit you should really avoid.
You should not use input() in Python 2. It is a security risk and 
although your program is not going to be used in earnest anywhere its a 
bad habit to get into. Better to use raw_input() and then convert to a 
number using int() - or float if thats what you need.

[In v3 raw_input has been renamed as input and the v2 input removed.]

> this fine? Also, how do I add a loop to this so that once one product
> has been dispensed the program asks the user if they would like to
> continue and purchase another product? /*

You should probably use a while loop.
You could use this pattern:

while True:   # means loop forever
    display menu
    get choice
    if choice is Exit:
        break    # drop out of the loop
    elif choice == ....

The final thing is that your coin counting code could
be made more concise by using a dictionary to store
the mapping of menu choice(A-D) to value:

coins = {'A': 0.1, 'B':0.2...}

Rather than all the individual variables.

Then the input code becomes:

print "Please select which ...."
choice = raw_input("Enter coin: ")
insert_coins = coins[choice]

Its a trade off of more code to define the data
or more code to read the input.

hth
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list