![](/img/trans.png)
[英]How do I make this caesar cipher work with capital letters using an IF statement in the FOR loop?
[英]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)
我一直弄錯了,我不知道該怎么辦。 我不想使用 for 循環只是一個 while 循環。 謝謝
您可以通過多種方式做到這一點。
如果我是你,我會使用isupper()
和sum()
生成器,
s = input("Type something...")
print(sum(1 for c in s if c.isupper()))
按照您的要求使用while ,
s = input("Type something...")
i = 0
capital = 0
while i < len(s):
if s[i].isupper():
capital+=1
i = i + 1
print(capital)
您正在將while
用於限制和計數,這將不起作用。
您必須使用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}')
但是,這段代碼非常復雜,更好的是@AlwaysSunny 的答案或@Samwise 的評論
您的while
循環當前是這樣編寫的,它將在第一個小寫字母處終止。 您需要在整個字符串上循環到 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}")
一種更簡單的方法是將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()))
嘗試使用這個:
text = input()
count=0
for letter in text:
if letter == letter.upper():
count+=1
print(letter, end=" ")
print(count-1)
我希望我已經解釋清楚了)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.