Python 计算大小写的数目
编写一个Python函数,该函数接受字符串并计算大写字母和小写字母的数量 这个代码有什么问题Python 计算大小写的数目,python,Python,编写一个Python函数,该函数接受字符串并计算大写字母和小写字母的数量 这个代码有什么问题 def up_low(sentence): uppcas=0 lowcas=0 for letter in sentence: while letter.isupper(): uppcas+=1 pass while letter.islower(): lowcas+=1
def up_low(sentence):
uppcas=0
lowcas=0
for letter in sentence:
while letter.isupper():
uppcas+=1
pass
while letter.islower():
lowcas+=1
pass
print ("original String: ", sentence)
print ("no of uppercase: ", uppcas)
print ("no of lowercase: ", lowcas)
您在for循环中使用了
而不是如果如果,则这些是无限循环。(您当前正在检查的字母在while主体内不会更改,因此它只会重新检查以前是小写的字母是否永远是小写的)
你想做的是
def up_low(sentence):
uppcas=0
lowcas=0
for letter in sentence:
if letter.isupper():
uppcas+=1
elif letter.islower(): # use elif so this is only checked if isupper() fails
lowcas+=1
print ("original String: ", sentence)
print ("no of uppercase: ", uppcas)
print ("no of lowercase: ", lowcas)
我删除了通行证
,如果您不想做任何事情,可以使用该通行证。如果你需要
当
s时,您可能会将通过
与中断
混淆,这将离开当前循环环境,但如果您只进行一次迭代,您通常希望使用if
您最好将第二个if
更改为elif
或在第一个if
中添加continue
——大写字母不应再次检查。@Gabip我同意elif
,但是在这里添加continue
并不能改善行为,只会混淆它的作用和需要它的原因。continue
的功能相同,它会将控件返回到for循环的开头,并且会跳过第二个检查,if letter.islower()
。很抱歉,我把你的“or”误读为“and”。