Search code examples
pythonfor-loopsumjesord

Adding ASCII Values together. Jython/Python


I need to get the word "COMPUTER". Convert each letter to its corresponding ASCII value (using For Loop). Then add the individual ASCII values together to get a sum.

I am entering "COMPUTER" as a parameter for 'text' when I launch the program.

So think COMPUTER = text

What i have so far:

def addASCIIValues(text):
  for char in text:
    AsciiArray = ord(char)
    print AsciiArray

  1. Text is entered as 'COMPUTER'
  2. for every character in "COMPUTER"
  3. Convert every character to its ASCII Value
  4. Add the values together
  5. Receive a total SUM
  6. Print sum

Please use simple code with no import functions.

I am using Jython but python responses would be ok aswell!


Solution

  • Part of your confusion might be because you have named the int returned by ord() AsciiArray. It is not an "array".

    This is simple using a list comprehension:

    word = 'COMPUTER'
    print sum([ord(c) for c in word])
    

    However you asked for specific steps:

    word = 'COMPUTER'
    SUM = 0
    for char in word:
        value = ord(char)
        SUM += value
    
    print SUM
    

    I should point out that generally UPPERCASE names are used for constants, and so the name SUM would not normally be considered good practice.