+ 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!!!!
6 Respostas
+ 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)
+ 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)
+ 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
+ 1
thnks
0
can i get a piece of code.
0
its not adding the output