Visiting every letter
Loop over a string and count the letters that pass a test. About 8 minutes.
Letter by letter
A for loop can walk along a string just like it walks along numbers. On each pass, a box takes the next letter, from the first to the last. You don't need to know how long the string is.
This is how you count things in text: how many vowels, how many spaces, how many capital letters. Make a counter that starts at zero, loop over the letters, and add one whenever a letter passes your test.
count = 0
for ch in s:
... # test ch hereIs it a capital letter?
How do you tell whether a letter is a capital? Letters have an order, just like in a dictionary: A comes before B, and B before C. Every capital letter lies between A and Z.
So the test is: is the letter at least A, and also at most Z? Both parts must be true, so you join them with and. Lowercase letters, digits and spaces all fall outside that range. Computers sort capitals before lowercase letters, which makes this test work.
if ch >= "A" and ch <= "Z":
count = count + 1- count
- 1
- letter
- H
H is between A and Z, so it is a capital. The count is 1.
How many capital letters are in "aBcDe"?
- A2
- B3
- C5
Show the answer
2. B and D are the capitals.
Count the capitals
Return how many capital letters (A to Z) are in the text. The text may also contain lowercase letters, digits and spaces.
s = "Hello World" → 2
0 ≤ length of s ≤ 1,000 · letters, digits and spaces