[Tutor] numbers from a name

ZIYAD A. M. AL-BATLY zamb at saudi.net.sa
Sun Sep 25 06:59:12 CEST 2005

On Sat, 2005-09-24 at 23:50 -0400, Goofball223 at wmconnect.com wrote:
> Hello
Hi Goofball...

> with the following program I would like it to be able to take a
> person's name  and then assign values to each letter and come up with
> a sum of all the letters in the name. for example if I entered bob. i
> would like the program to be able to print bob and then print the
> total of bob which would be 2 + 15 + 2 = 18.
It should be 19, not 18.

> import string 
You don't need the "string" module for something this simple.  Just

> def main(): 
>    value = (raw_input("Please enter your first name"))
Why the parenthesis?  This is better:
    value = raw_input("Please enter your first name: ")

Also, after that you can convert the whole string to lower letters in
one step:
    value = value.lower()

A good resource for information about Python's built-ins and modules is
to start the Python shell and type "help(something)", where "something"
is what you want more info about.

In the above example, "raw_input" will return an object of type "str".
Type "help(str)" and see a lot of things you could do to/with "str"
objects!  (By the way, I found that "raw_input" returns "str" by typing
"help(raw_input) in Python! :) )

>     table = {'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5, 'f' : 6,
> 'g' : 7, 'h' : 8, 'i' : 9, 'j' : 10, 'k' : 11, 'l' : 12, 'm' : 13,
> 'n' : 14, 'o' : 15, 'p' : 16, 'q' : 17, 'r' : 18, 's' : 19, 't' : 20,
> 'u' :         21, 'v' : 22, 'w' : 23, 'x' : 24, 'y' : 25, 'z' : 26}
You could write a loop to create the "table" for you.  Though, It will
be slower than the above method and will consume more system resources.
But it will be much easier on you.   (A Real Programmer is a lazy one!:)
Just kidding!)

>     total = 0
>     name = list(name)
What's "name" for?  Also, "name" never used before!  Did you mean
"name=list(value)"?  But I don't see how's that going to help.
>     for string in name:
>         total += table[string.lower()]
>     print "The total of your name is:", total 
"string" is the name of a module!  You can't use it here _if_ you
imported that module.  And as mentioned above, what's "name"?

Try this:
    for x in value:
        total += table[x]
    print "The total of your name is:", total

"x" will iterate for each item (in this case, letter) in "value" which
holds the lowered case input.  "table" have each letter assigned to a
number.  "table[x]" will look-up "table" and _return_ the _number_
assigned to the letter that is held in "x".

If you didn't understand this just ask here again and many well be glad
to help.

> main() 


More information about the Tutor mailing list