2012-04-22 52 views
-1

我想要完成的是第一個文本在1秒後出現。然後2等。直到10.然後當時間等於10時,時間減少,所以文本出現9秒後,然後8等如何更改打印文本的速度(python)

我該如何解決這個代碼,以便它能正常工作?

錯誤:

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 我該如何設置它,以便程序將時間增加到十,然後減少到零,然後再次增加?

回答

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 
    
  • 僅從timefrom time import sleep導入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

第三種解決方案可能是最好的 – Wes 2012-04-22 03:46:23

+0

謝謝你,先生。 ;) – enrique2334 2012-04-22 04:12:30

4

你重新定義「時間」導入後...

嘗試使用不同的變量名。

3

您的time變量與您導入的模塊(time)衝突。您可以使用curTimemyTime作爲您的變量名稱。