【问题标题】:Method goes into an infinite loop方法进入无限循环
【发布时间】:2017-06-28 13:14:03
【问题描述】:

我正在尝试调用递归方法并在while 条件为False 时退出调用它。虽然,我得到的是当 COUNT_NUM 为 0 时,该方法只会不断重复并返回 prints

不知道我做错了什么

import urllib.request
from bs4 import BeautifulSoup

URL = input("Enter URL: ")
COUNT = input("Enter count: ")
POS = input("Enter position: ")

def retrieveNames(url, count=1, position=1):
    """ Retrieves a name from url """

    POSITION_NUM = int(position)
    COUNT_NUM = int(count)

    if (POSITION_NUM< 1): return

    html = urllib.request.urlopen(url).read()
    soup = BeautifulSoup(html, "html.parser")

    tags = soup("a")
    countNum = COUNT_NUM - 1

    tag = tags[POSITION_NUM-1]
    print("COUNT:", countNum > 0)
    while countNum > 0:
        retrieveNames(tag.get("href"), countNum, position)

    print(tag.contents[0])
    return

retrieveNames(URL, COUNT, POS)

【问题讨论】:

  • 您可能希望将while count &gt; 0: 替换为if count &gt; 0:。否则while 循环将在count &gt; 0 时永远运行。或者在 while 循环内设置 count -= 1 而不是在外部设置 count = COUNT_NUM - 1
  • 好的,声明的count 变量应该有不同的名称,但count &gt; 0 返回False。那么它是如何保持循环的呢? ://
  • @JimFasarakisHilliard 你能详细说明一下吗?不知道它是如何做到的,因为 while 循环条件是错误的
  • 你的循环本质上是while count &gt; 0: do nothing。你根本没有递减count。一旦开始,就永远不会停止。
  • @RolandJegorov count &gt; 0 对于 一些 的调用 retrieveNames 的计算结果为 False,即当您将参数 count 传递给它时,该参数为零。但是,在您的 while 循环中,您将永远这样做。

标签: python python-3.x


【解决方案1】:

您正在陷入无限循环,因为您正在递归调用您的函数,这意味着您的变量 countnum 现在存在于多个范围内:原始函数调用和递归调用。这意味着当您调用retrieveNames 时countnum 发生的任何事情都不会影响while 循环中countnum 的值。因此,您将永远无法摆脱 while 循环。 所以你想要做的是要么返回countnum:

while countNum > 0:
    countNum = retrieveNames(tag.get("href"), countNum, position)
return countNum

或将 while 语句更改为 if 语句。

【讨论】:

    猜你喜欢
    • 2013-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多