+ 1

List value in python

i want to make a program that will ask the user to input a word and will give the sum in output. suppose the user inputs the word "java", now in english alphabets j comes at 10, a at 1, v at 22 and again a at 1 so the output will be the sum of it i.e., 10+1+22+1=34 . so how can i make it. i am begginer. plz help!!!!

3rd Sep 2017, 3:39 AM
sarthak tyagi
sarthak tyagi - avatar
6 Respuestas
+ 2
Most of the code is already in my first post, but... word = input("Enter a word: ").strip().lower() total = 0 for l in word: total += ord(l) - 96 print(total) OR: word = input("Enter a word: ").strip().lower() total = sum([(ord(l)-96) for l in word]) print(total)
3rd Sep 2017, 7:22 AM
ChaoticDawg
ChaoticDawg - avatar
+ 3
You could create a python dictionary of the alphabet and get the value of each letter from that dictionary. letters = { 'a' : 1, 'b': 2, 'c': 3, ......etc} Get the input from the user: word = input("Enter a word: ").strip() # strip removes leading and trailing spaces loop over each letter in the word: for l in word: # do stuff with the letter here print(letters[l]) # letters[l] gets the value for the corresponding letter in the letters dictionary Some other helpful functions might be: lower() # get the lowercase value of the string "A".lower() returns "a" upper() # gets the uppercase of the string You could also get the ascii value of the letter instead of using a dictionary: 'a' = 97 ord('a') - 96 will return 1 for a word = input("Enter a word: ").strip().lower() for l in word: print(ord(l)-96)
3rd Sep 2017, 5:03 AM
ChaoticDawg
ChaoticDawg - avatar
+ 3
It just outputs the sum of the value of all the letters. If you input "java" it outputs 34 if you input "happy" it outputs 66
3rd Sep 2017, 7:19 AM
ChaoticDawg
ChaoticDawg - avatar
+ 1
thnks
3rd Sep 2017, 7:22 AM
sarthak tyagi
sarthak tyagi - avatar
0
can i get a piece of code.
3rd Sep 2017, 6:39 AM
sarthak tyagi
sarthak tyagi - avatar
0
its not adding the output
3rd Sep 2017, 7:12 AM
sarthak tyagi
sarthak tyagi - avatar