-2

如何将for循环更改为while循环。for使用和while循环之间的显着区别是什么?

S="I had a cat named amanda when I was little"
count = 0
for i in S:
    if i =="a":
        count += 1
print (count)
4

3 回答 3

3

以下是相同代码的 while 循环实现。

i = 0
count = 0
while i < len(S):
    if S[i] == 'a':
        count += 1
    i += 1
print count
于 2012-10-20T05:31:23.813 回答
1

您需要一个计数器,每次“当计数器 < len(S)”时都会递增

这是一个开始:

index = 0
count = 0
while index < len(S):
    #do something with index and S ...
    index += 1
于 2012-10-20T05:15:30.673 回答
0

您也可以通过空字符串/列表/字典的布尔性质来做到这一点。

S="I had a cat named amanda when I was little"
count = 0
while S:
    # pop the first character off of the string
    ch, S = S[0], S[1:]
    if ch == "a":
        count += 1
print (count)
于 2012-10-20T05:36:05.693 回答