Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
While loop
#1
Hi guys.

I am quite new to the whole coding, and hope you could help me with this little piece.
I have this small script, which allows me to open random sites in my browser with 5 - 20 seconds interval.

I want to have a while loop, so it stops after it have repeated it for 5 times. But it wont work - Is it because I should use a for loop ?

Here is the code.
import webbrowser
import time
import random

repeat = 4

while repeat < 4: 
    sites = random.choice(['google.com', 'youtube.com'])
    visit = "http://{}".format(sites)
    webbrowser.open(visit)
    seconds = random.randrange(5, 20)
    time.sleep(seconds)

    repeat += 1
    repeat = repeat + 1 
Thank you! :)
Reply
#2
here you go.

import webbrowser
import time
import random

repeat = 4

while True:
    for i in range(repeat):
        sites = random.choice(['google.com', 'youtube.com'])
        visit = "http://{}".format(sites)
        webbrowser.open(visit)
        seconds = random.randrange(5, 20)
        time.sleep(seconds)
Reply
#3
(Aug-02-2019, 03:37 PM)kasper1903 Wrote: I want to have a while loop, so it stops after it have repeated it for 5 times. But it wont work - Is it because I should use a for loop ?
The reason it won't work is because the while loop will only play while 4 is less than it. repeat is equal to four so it won't work. Do this
import webbrowser
import time
import random

for _ in range(1, 6) #This will repeat 5 times. The underscore is there because the value it returns is not needed
    sites = random.choice(['google.com', 'youtube.com'])
    visit = "http://{}".format(sites)
    webbrowser.open(visit)
    seconds = random.randrange(5, 20)
    time.sleep(seconds)
Reply
#4
Thank you so much the both of you! :D
It helped alot!

Have an awesome day!
Reply
#5
If you like while,
max_count = 4
count = 1
while count < max_count :
    count +=1
    ...
The count +=1 is shorthand for count = count + 1
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020