我正在使用"随机"来制作代码来更改变量每次迭代中的函数,不断检查变量是否等于特定的预定义值。如果相等,代码将停止,记录达到该值所需的时间。代码工作正常并且正如预期的那样,直到我介绍了我的计时方法,使用time.time()。
为什么我收到错误声明我的语法在" start = time.time()"无效(第5行)?
我在其他代码中测试了相同的设置,它完美无缺。我该如何解决这个问题?
提前致谢。
import random
import time
VARIABLE = int(random.randint(1, 16))
function = int(0)
start = time.time()
while True:
function = int(random.randint(1,16))
if not VARIABLE == int("0"):
if function == int("1"):
VARIABLE = int(VARIABLE) + int(random.randint(1,1000))
if function == int("2"):
VARIABLE = int(VARIABLE) - int(random.randint(1,1000))
if function == int("3"):
VARIABLE = int(VARIABLE) * int(random.randint(1,1000))
if function == int("4"):
VARIABLE = int(VARIABLE) / int(random.randint(1,1000))
if function == int("5"):
VARIABLE = int(random.randint(1,1000)) / int(VARIABLE)
if function == int("6"):
VARIABLE = int(VARIABLE) + int(random.randint(1,1000))
if function == int("7"):
VARIABLE = int(random.randint(1,1000)) - int(VARIABLE)
if function == int("8"):
VARIABLE = int(VARIABLE) ^ int(random.randint(1,1000))
if function == int("9"):
VARIABLE = int(random.randint(1,1000)) ^ int(VARIABLE)
if function == int("10"):
VARIABLE = (int(VARIABLE) * int(random.randint(1,1000)))^2
if function == int("11"):
VARIABLE = (int(VARIABLE) + int(random.randint(1,1000)))^2
if function == int("12"):
VARIABLE = (int(VARIABLE) - int(random.randint(1,1000)))^2
if function == int("13"):
VARIABLE = (int(VARIABLE) / int(random.randint(1,1000)))^2
if function == int("14"):
VARIABLE = (int(random.randint(1,1000))/int(VARIABLE))^2
if function == int("15"):
VARIABLE = (int(random.randint(1,1000)) - int(VARIABLE))^2
if function == int("16"):
VARIABLE = (int(VARIABLE) ^ int(random.randint(1,1000)))^2
if function == int("16"):
VARIABLE = (int(random.randint(1,1000))^int(VARIABLE))^2
print int(VARIABLE)
time.sleep(.75)
if VARIABLE == int("42"):
end = time.time()
print("Task completed.")
break
print("This time, we completed the task in "+(end-start)+ "seconds.")
答案 0 :(得分:2)
虽然代码的time.time()
部分适用于我,但在line 24
上,您无法使用^
来表示指数。在python中,您使用**
。正如Nick在下面指出的,^
是python中的按位exclusive or operator。