Python while循环如何知道何时停止?
我正在修Udacity CS101课程(Python)。下面是“第2课:问题集-查找最后一个”中的问题和解决方案 我的问题:下面代码中的while循环如何知道何时停止Python while循环如何知道何时停止?,python,while-loop,Python,While Loop,我正在修Udacity CS101课程(Python)。下面是“第2课:问题集-查找最后一个”中的问题和解决方案 我的问题:下面代码中的while循环如何知道何时停止 # Define a procedure, find_last, that takes as input # two strings, a search string and a target string, # and returns the last position in the search string # where
# Define a procedure, find_last, that takes as input
# two strings, a search string and a target string,
# and returns the last position in the search string
# where the target string appears, or -1 if there
# are no occurences.
#
# Example: find_last('aaaa', 'a') returns 3
# Make sure your procedure has a return statement.
def find_last(s,t):
last_pos = -1
while True:
pos = s.find(t, last_pos+1)
if pos == -1:
return last_pos
last_pos = pos
函数退出时,
while
循环停止,执行return
语句时,函数退出
return
语句在s.find()返回-1时执行,这意味着从last_pos+1
开始搜索时,在s
中找不到t
。它从不停止。当执行return
语句时,它被强制退出。当你从函数中return
时,函数的执行被终止。现在谁在使用procedure
这个词?@devnull自70年代以来就没有在校外编程过的教授:p此处有一个过程的严格定义,但由于函数返回一个值,此处未实现该定义。