我是 Python 新手,最近无法很好地使用 while 循环 - 变量没有更新新值!
我创建了一个 while 循环,当发现另一个 URL 时,应在其中更新 URL。我还添加了一个“times”变量来测试循环执行的次数。 (计数 = 4 => 最后版本次数 = 4)。然而,“次数”确实改变了,但 URL 只改变了 1 次。
URL = input('Enter - ')
count = input('Enter count: ')
pos = input('Enter position: ')
times = 0
links = list()
while times < int(count):
html = urlopen(URL, context=ctx).read()
soup = BeautifulSoup(html, "html.parser")
tags = soup('a')
for tag in tags:
link = tag.get('href',None)
links.append(link)
URL = links[int(pos) - 1]
times = times + 1
name = re.findall('known_by_(.+).html',URL)
print(name)
我希望更新 URL,并且循环再次运行 4 次,但只得到第一次循环运行时的结果。同时“times”变量被添加了足够的 4 次。
最佳答案
您的循环看起来应该运行 count
次,每次都执行完全相同的操作。但是,最后两行没有缩进,因此它们位于循环之外。这意味着它们只会在循环完成后运行一次。
如果您想在每次循环运行时运行最后两行,则需要将它们缩进到与 times = times + 1
相同的级别。
关于python - while循环不更新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55332323/