如何将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)
如何将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)
以下是相同代码的 while 循环实现。
i = 0
count = 0
while i < len(S):
if S[i] == 'a':
count += 1
i += 1
print count
您需要一个计数器,每次“当计数器 < len(S)”时都会递增
这是一个开始:
index = 0
count = 0
while index < len(S):
#do something with index and S ...
index += 1
您也可以通过空字符串/列表/字典的布尔性质来做到这一点。
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)