Reputation: 21
I'm new to Python and recently cannot work well with while loop - the variable did not update new value!
I created a while loop within which URL shall be updated when found another URL. I also add a 'times' variable to test the number of time the loop do. (count = 4 => the last version times = 4). However, 'times' did change but URL just change 1 time.
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)
I expect the URL to be updated and the loop ran again for 4 times but only get the result of the first loop run time. Meanwhile the 'times' variable got added enough 4 times.
Upvotes: 1
Views: 707
Reputation: 18625
Your loop looks like it should run count
times, doing the exact same thing each time. However, the last two lines are not indented, so they are outside the loop. That means they will only run once, when the loop has finished.
If you want to run the last two lines each time the loop runs, you need to indent them to the same level as times = times + 1
.
Upvotes: 1