-1

我想要完成的是第一个文本在 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)

所以我改变了程序,所以我几乎可以正常工作。它的作用是计数到 10,然后计数到 9,然后返回到 10。例如。1,2,3,4,5,6,7,8,9,10,9,10,9,10 我如何设置它以便程序将时间增加到十然后减少到零然后再次增加?

4

3 回答 3

5

您正在time用自己的time变量(第 4 行)覆盖导入的模块(第 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 tmtm.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仅从timewith导入from time import sleepsleep(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)
于 2012-04-22T03:41:46.607 回答
4

导入后您正在重新定义“时间”...

尝试使用不同的变量名。

于 2012-04-22T03:41:58.297 回答
3

您的time变量与time您导入的模块 ( ) 冲突。您可以使用curTimeormyTime作为变量名。

于 2012-04-22T03:42:22.633 回答