Aditya Shukla Aditya Shukla - 4 months ago 11
Python Question

Compiler returning invalid syntax error when using time.ctime()

So today I was writing a relatively childish program in Python for opening a recreational video on YouTube after a certain period of time. More like a break time thing so that it opened a random pick from a list of URLs. Here's the code :

import os
import sys
import webbrowser
from time import *
import random

print("Hello! This program was started at " time.ctime())

totalBreaks = 5000
breaksTaken = 0

url = ['http://www.youtube.com/watch?v=OXWrjWDQh7Q', 'https://www.youtube.com/watch? v=yNLdblFQqsw', 'https://www.youtube.com/watch?v=tD4HCZe-tew', 'https://www.youtube.com/watch?v=GTyN-DB_v5M', 'https://www.youtube.com/watch?v=n49qi-dU9IE', 'https://www.youtube.com/watch?v=2iFa5We6zqw', 'https://www.youtube.com/watch?v=KEI4qSrkPAs', 'https://www.youtube.com/watch?v=yzTuBuRdAyA', 'https://www.youtube.com/watch?v=_kqQDCxRCzM', 'https://www.youtube.com/watch?v=u2cphuMbqfc']

while (breaksTaken > totalBreaks) :
time.sleep(60)
webbroswer.open(choice.random(url))

Answer
import os
import sys
import webbrowser
import time

# Added explanation #0:
# Always try to avoid import *
# and if still you do 'from time import sleep' or 'from time import *'
# then there will be different namespace, so you'd use: sleep(1)
# but not time.sleep(1) -- and this is not Pythonic way.

import random

print("Hello! This program was started at %s " % time.ctime())

# Added explanation #1:
# You should concatenate output in print ^^^^^^^^^^ statement

totalBreaks = 5000
breaksTaken = 0

url = ['http://www.youtube.com/watch?v=OXWrjWDQh7Q',
       'https://www.youtube.com/watch?v=yNLdblFQqsw',
       'https://www.youtube.com/watch?v=tD4HCZe-tew']

while (breaksTaken > totalBreaks):
    time.sleep(60)
    webbroswer.open(random.choice(url))
# Added explanation #2:
# You should use random.choice(), not a choice.random()

# That's all, folks!
Comments