Style
A few things can be easily detected/improved in your code regarding the style. If you want, you'll find various tools to perform checks automatically : pep8
, pyflakes
, pychecker
. They'll give you a great deal of interesting information, from imported module xxx is not used
, to bad indentation
via missing documentation
, wrong spacing
and invalid constant name
. Also, it might be good for you to know that in Python, there is a style guide called PEP8 and it's definitely worth a read.
After fixing everything to make the tools happy, your code looks like:
"""Module docstring"""
NAMES = {
'a': 'awesome',
'b': 'bold',
'c': 'curious',
'd': 'delightful',
'e': 'emotional',
'f': 'fearless',
'g': 'gifted',
'h': 'helpful',
'i': 'imaginary',
'j': 'joyful',
'k': 'kindhearted',
'l': 'lovable',
'm': 'memorable',
'n': 'naughty',
'o': 'open',
'p': 'playful',
'q': 'quarrelsome',
'r': 'reliable',
's': 'serious',
't': 'thoughtful',
'u': 'unique',
'v': 'victorious',
'w': 'wise',
'x': 'xerox copy',
'y': 'yummy',
'z': 'zealous'
}
def main():
"""Main function"""
i = j = 0
user = raw_input("What is your name?: ")
print ""
while i < len(user):
while j < len(NAMES):
if user[i] == NAMES.keys()[j]:
print " " + user[i] + ' = ' + NAMES.values()[j]
j = j + 1
while j != 0:
j = 0
i = i + 1
if __name__ == '__main__':
main()
Loops
Your are going through your containers (user
and names
) with a while
loop. This is a bit impractical but if you really want to do so, it is clearer to initialise the variable you are going to loop with before the loop so that you not have to try to reset it after the loop.
i = 0
while i < len(user):
j = 0
while j < len(NAMES):
if user[i] == NAMES.keys()[j]:
print " " + user[i] + ' = ' + NAMES.values()[j]
j = j + 1
i = i + 1
Even better, the range
function can generate the values your are looking for so that you do not need to do the incrementation yourself :
for i in range(len(user)):
for j in range(len(NAMES)):
if user[i] == NAMES.keys()[j]:
print " " + user[i] + ' = ' + NAMES.values()[j]
but Python provides you an even better way to iterate over containers :
for c in user:
for j in range(len(NAMES)):
if c == NAMES.keys()[j]:
print " " + c + ' = ' + NAMES.values()[j]
Also, because you are using a dictionary, there is no need to loop over NAMES
. You could lookup keys in the dict naturally:
for c in user:
if c in NAMES:
print " " + c + ' = ' + NAMES[c]