我想要完成的是1秒钟后出现的第一个文字。那么2,等等。直到10.然后当时间等于10时,时间减少,所以文本出现在9秒后,然后是8等。
我如何修复此代码以使其正常工作?
错误:
Traceback (most recent call last):
File "C:/Users/Eric/Dropbox/time.py", line 13, in <module>
time.sleep(time)
AttributeError: 'int' object has no attribute 'sleep'
代码:
import time
x = 1
t = 1
time = t + 1
while x == 1:
print time
if time >=10:
time = t - 1
elif time <= 0:
time = t + 1
time.sleep(time)
编辑:
import time
x = 1
t = 1
time1 = 0
while x == 1:
if time1 == 10:
time1 = time1 - 1
elif time1 == 0:
time1 = time1 + 1
else :
time1 = time1 + 1
print time1
time.sleep(time1)
所以我改变了abit的程序,所以我几乎正常工作。它的作用是数到10,然后是9然后回到10。 恩。 1,2,3,4,5,6,7,8,9,10,9,10,9,10 如何设置它以便程序将时间增加到10然后减少到零然后再次增加?
答案 0 :(得分:5)
您将通过自己的time
变量(第4行)覆盖导入的time
模块(第1行)。你可以:
将您的time
变量重命名为其他
import time
x = 1
t = 1
time_passed = t + 1 # use "time_passed" instead of "time" for example
while x == 1:
print time_passed
if time_passed >= 10:
time_passed = t - 1
elif time_passed <= 0:
time_passed = t + 1
time.sleep(time_passed)
使用time
使用import time as tm
tm.sleep(time)
模块进行别名
import time as tm # alias the time module as "tm" for example
x = 1
t = 1
time = t + 1
while x == 1:
print time
if time >= 10:
time = t - 1
elif time <= 0:
time = t + 1
tm.sleep(time) # use "tm" to refer to the module
仅使用sleep
从time
导入from time import sleep
并改为使用sleep(time)
from time import sleep # only import "sleep" from time, not the whole module
x = 1
t = 1
time = t + 1
while x == 1:
print time
if time >= 10:
time = t - 1
elif time <= 0:
time = t + 1
sleep(time) # use "sleep" directly
修复此问题后,您还需要以某种方式记住,您需要在下一次迭代时增加或减少时间。例如:
from time import sleep
x = 1
t = 1
time = t + 1
incr = True
while x == 1:
print time
if time >= 10:
time = 9
incr = False
elif time <= 0:
time = t + 1
incr = True
else:
if incr:
time = time + 1
else:
time = time - 1
sleep(time)
答案 1 :(得分:4)
导入后,您正在重新定义“时间”...
尝试使用其他变量名称。
答案 2 :(得分:3)
您的time
变量与您导入的模块(time
)冲突。您可以使用curTime
或myTime
代替您的变量名称。