简体   繁体   中英

How do I count the number of capital letters using a while loop

s = input()
i = 0

while i < len(s) and (s[i]) < "A" or "Z" < s([i]):
    print(i)
    

I keep getting this wrong and I'm not sure what to do. I Do not want to use a for loop just a while loop. Thank you

You can do it by many ways.

If I were you I will do it using isupper() and sum() generator,

s = input("Type something...")
print(sum(1 for c in s if c.isupper()))

Using while as you asked,

s = input("Type something...")
i = 0
capital = 0
while i < len(s):
    if s[i].isupper():
        capital+=1
    i = i + 1
print(capital)

You are using the while for both the limit and the counting which won't work.

You have to use the while for the limit and an if for the counting:

s = input()

i = 0
count = 0
while i < len(s):
    print(i)
    if "A" <= s[i] <= "Z":
        count += 1
    i = i + 1

print(f'Capitals in "{s}" = {count}')

However, this code is very complicated and better is the answer from @AlwaysSunny or the comment from @Samwise

Your while loop is currently written such that it will terminate at the first lowercase letter. You need the loop to go over the entire string, but keep count of uppercase letters as it goes.

s = input()
i = 0
c = 0

while i < len(s):
    if "A" <= s[i] <= "Z":
        c = c + 1  # c only goes up on capital letters
    i = i + 1      # i goes up on every letter
    print(i, c)

print(f"Capital letters: {c}")

An easier method is to use the sum function along with isupper :

s = input()
print(f"Capital letters: {sum(c.isupper() for c in s)}")
def Capital(In):
    return sum([l.isupper() for l in In])

print(Capital(input()))

Try use this:

text = input()
count=0
for letter in text:
    if letter == letter.upper():
        count+=1
        print(letter, end=" ")
print(count-1)

I hope I have explained clearly)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM