+ 1

Having trouble returning x

I wrote this code to take input, and then check each character of the string and add numers together dependant upon which letter it reads: W = input("Enter a Word: ") print (W) r = 0 for i in W: r += 1 print (r) This is how I take the word from the user and find the length of the word. This next bit of code is a little wet but its supposed to check each letter in the string, and depending on that letter; a number is added to x: w1 =[W] i = 0 x = 0 while i < r: if (w1 [0][i]) == 'A' or 'a' or 'J' or 'j' or 'S' or 's': i += 1 x += 1 elif (w1 [0][i]) == 'B' or 'b' or 'K' or 'k' or 'T' or 't': i += 1 x += 2 elif (w1 [0][i]) == 'C' or 'c' or 'L' or 'l' or 'U' or 'u': i += 1 x += 3 Print (x) Let's say "ABC" is input. It should add 1 to x for a, +2 for b and ×3 for c making x = 6. However when I try it, it will only give 3 or however many letters are in the input. Can anyone tell me why or how to adjust this so it gives me 6 as intended?

19th Dec 2020, 12:00 AM
jonathan
jonathan - avatar
2 Answers
+ 3
There no need for the first loop, python has a function called len() that returns the length of the string....and..in your second while loop, your trying to access the individual character as though it was a 2 dimensional array, which it isn't..so.....this is how I would do what your trying to do... W = input("Enter a Word: ") x = 0 for c in W: if c.lower() in ['a', 'j', 's']: x += 1 elif c.lower() in ['b', 'k', 't']: x += 2 elif c.lower() in ['c', 'l', 'u']: x += 3 print(x) or... mydict = {'a': 1, 'j': 1, 's': 1, 'b': 2, 'k': 2, 't': 2, 'c': 3, 'l': 3, 'u': 3} z = 0 for c in W: z += mydict.get(c.lower(), 0) print(z)
19th Dec 2020, 1:07 AM
rodwynnejones
rodwynnejones - avatar
0
I'm sorry, +3 not × ^^
19th Dec 2020, 12:01 AM
jonathan
jonathan - avatar