Python While 循环 - 变量未更新? [英] Python While Loop - Variable Not Updating?
问题描述
此代码只是在另一个字符串中查找一个字符串,并返回搜索字符串中出现的最后一个位置,如果未找到,则返回 -1.
This code simply looks for a string in another string and returns the last postion of the occurance in the search string or -1 if its is not found.
我不明白为什么我的变量 next_y
没有更新,因为 pos
是计算 next_y
的输入.我的想法是,如果我更新 pos
那么 next_y
也应该更新.取而代之的是 pos
被更新并永远留在循环中.
I don't understand why my variable next_y
is not updating considering that pos
is an input into computation of next_y
. My thought that is that if I update pos
then next_y
should also update. Instead pos
gets updated and remains in the loop forever.
def find_last(x,y):
if x.find(y) == -1:
return -1
pos = x.find(y)
next_y = x.find(y, pos + 1)
while next_y != -1:
pos = pos + next_y
return pos
search = 'tom ran up but tom fell down'
target = 'tom'
print(find_last(search,target))
推荐答案
您不会在 while 循环中更改 next_y 的值,因此它的值不会更新.next_y 的值计算一次并永远比较(或仅比较一次).要更新此值,您应该在循环中调用 'next_y = x.find(y, pos + 1)'.
You don't change the value of next_y in the while loop, so its value isn't updated. Value of next_y is calculated once and compared for ever (or only once). To update this value you should call 'next_y = x.find(y, pos + 1)' in the loop.
def find_last(x,y):
if x.find(y) == -1:
return -1
pos = x.find(y)
next_y = x.find(y, pos + 1)
while next_y != -1:
pos = pos + next_y
next_y = x.find(y, pos + 1)
return pos
search = 'tom ran up but tom fell down'
target = 'tom'
print(find_last(search,target))
这篇关于Python While 循环 - 变量未更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!