I am trying to write a program to find the total number of letters in a sentence. I would like to know why my program is wrong. This is what I tried:
words = ["hi", "how", "are", "you"]
alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
y = 0
for i in words:
for x in alphabet:
n = words.count(x)
y = y + n
print (y)
This program just returns 4 zeroes.
From my point of view, the program should run like this: In the first run of the loop, i = "hi" and x = "a" . The number of "a"'s is stored in the variable n, which is then stored in the variable y. Then x takes the value "b", "c", etc until it runs trough the whole alphabet. Then the next thing is repeated until i moves to the second word.
The reason your program is not working is - you are iterating the words
with each word as i
, but in the inner loop you are doing words.count()
instead of i.count()
.
This is how your for loop should look like -
for i in words:
for x in alphabet:
n = i.count(x)
y = y + n
print (y)
Change
n = words.count(x)
to
n = i.count(x)
does the trick.
Reason
You are saying i
is your one word in each iteration.So you have to use i.count(x)
to get count of x
in i
I think you should use n = i.count(x)
, not "n = words.count(x)"
words = ["hi", "how", "are", "you"]
alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
y = 0
for i in words:
for x in alphabet:
n = i.count(x)
y = y + n
print (y)
Output
11
sentence = "hi how are you"
count = sum(1 for c in sentence if c.isalpha())
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.