Python 如何跳出函数并返回到循环中?

Python 如何跳出函数并返回到循环中?,python,Python,我目前正在制作一个web生成器,它将根据GIPHY API生成一个随机gif。我遇到了一个问题,当api返回结果为0时,我测试了一个案例 def get_image_link(link): global flag set_count = 0 r = requests.get(link) api_response = json.loads(r.text) response = api_response['data'] if not response: print('GIPHY API re

我目前正在制作一个web生成器,它将根据GIPHY API生成一个随机gif。我遇到了一个问题,当api返回结果为0时,我测试了一个案例

def get_image_link(link):
global flag
set_count = 0
r = requests.get(link)
api_response = json.loads(r.text)
response = api_response['data']
if not response:
    print('GIPHY API returned no results... finding another word...')
    pass
elif response:
    for set in response:
        set_count += 1
    random_gif_num = random.randint(0, set_count) - 1
    try:
        flag = True
        return response[random_gif_num]['images']['original']['url']
    except TypeError:
        print(TypeError + '... rerunning application...')
        pass
不标记时:
获取图像链接(获取随机查询())


本质上,如果返回的结果中没有数据,我希望它重试函数以获取另一个单词。当返回结果为0的单词时,该程序工作,但当返回结果为0的单词时,我得到一个
TypeError
,它不会返回到循环中。我确信它会这样做,因为它不会中断函数,而是返回一个
[]
类型。如何中断函数并返回while循环,以便生成另一个结果?谢谢。

您可以将捕获异常移到功能之外,即:

while not flag:
    try:
       get_image_link(get_random_query())
    except TypeError:
        flag = False
        print('TypeError... rerunning application...')
        pass

您可以将捕获异常移动到函数外部,即:

while not flag:
    try:
       get_image_link(get_random_query())
    except TypeError:
        flag = False
        print('TypeError... rerunning application...')
        pass
将标志重置为false

try:
    flag = True
    return response[random_gif_num]['images']['original']['url']
except TypeError:
    flag = false
    print(TypeError + '... rerunning application...')
    pass
将标志重置为false

try:
    flag = True
    return response[random_gif_num]['images']['original']['url']
except TypeError:
    flag = false
    print(TypeError + '... rerunning application...')
    pass

谢谢你的回复,即使当它运行并试图找到另一个单词时,我仍然收到一个打字错误,它停止了文件。知道为什么吗?@Lewis我猜,它与异常无关,而是与
flag
变量有关,该变量被设置为
True
出于某种原因,get\u image\u link()在其他地方被调用。您认为响应变量即使等于[]也能访问循环的另一部分吗?感谢您的回复,即使它运行并尝试查找另一个单词,我仍然会收到一个TypeError,它会停止文件。知道为什么吗?@Lewis我猜,它与异常无关,而是与
flag
变量有关,该变量被设置为
True
出于某种原因,get\u image\u link()在其他地方被调用。你认为响应变量即使等于[]也能访问循环的另一部分吗?我尝试了一下,很多时候它都能工作,但是,在某些情况下,我会得到TypeError,它会取消我的代码。知道为什么吗?@Lewis问题在于打印,在这里你试图用一个字符串连接一个异常对象,这毫无意义,把它改成类似于打印('TypeError…重新运行应用程序…')我尝试了一下,但是很多时候它都能工作,在某些情况下,我会得到TypeError,它会取消我的代码。知道为什么吗?@Lewis问题在于打印,在这里你试图用一个字符串连接一个异常对象,这毫无意义,把它改成类似于打印('TypeError…重新运行应用程序…')