简体   繁体   English

如何使用while循环计算大写字母的数量

[英]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.我不想使用 for 循环只是一个 while 循环。 Thank you谢谢

You can do it by many ways.您可以通过多种方式做到这一点。

If I were you I will do it using isupper() and sum() generator,如果我是你,我会使用isupper()sum()生成器,

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

Using while as you asked,按照您的要求使用while

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.您正在将while用于限制和计数,这将不起作用。

You have to use the while for the limit and an if for the counting:您必须使用while进行限制,使用if进行计数:

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但是,这段代码非常复杂,更好的是@AlwaysSunny 的答案或@Samwise 的评论

Your while loop is currently written such that it will terminate at the first lowercase letter.您的while循环当前是这样编写的,它将在第一个小写字母处终止。 You need the loop to go over the entire string, but keep count of uppercase letters as it goes.您需要在整个字符串上循环到 go,但要保持大写字母的数量。

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 :一种更简单的方法是将sum function 与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)我希望我已经解释清楚了)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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