Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Think of the numpad number layout.

hvd = horizontal, vertical or diagonal

coord = 1,2 or 3 if horizontal or vertical and 1 or 2 if diagonal (1 is up, 2 is down)...

hello('v', 2) - Asking for the second vertical column etc

def hello(hvd, coord):
    if hvd == 'h':
        print "horizontal it is"
        if coord == 1:
            print "789"
        elif coord == 2:
            print "456"
        elif coord == 3:
            print "789"
        else:
            print "coord is wrong"
    elif hvd == 'v':
        print "vertical it is"
        if coord == 1:
            print "741"
        elif coord == 2:
            print "852"
        elif coord == 3:
            print "963"
        else:
            print "coord is wrong"
    elif hvd == 'd':
        print "diagonal it is"
        if coord == 1:
            print "159"
        elif coord == 2:
            print "753"
        else:
            print "coord is wrong"
    else:
        print "hvd is wrong"

I just want a critique on this function. I am interested in knowing if there is a nicer way to do what I am doing and if there is anything wrong with my code.

It seems quite hard to look at especially since it contains place holder statements and the actual statements I want might be 10 lines long each... Would be unwieldy surely?

share|improve this question
add comment

1 Answer

A nicer way to do the same would be to use a dictionary:

def hello(hvd, coord):        
    d = {'h': ["789", "456", "123"],
         'v': ["741", "852", "963"],   
         'd': ["159", "753"]}
    try:
        print d[hvd][coord-1]
    except IndexError:
        print "coord is wrong"
    except KeyError:
        print "hvd is wrong"
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.