How can I make the While True line go a bit slower
本问题已经有最佳答案,请猛点这里访问。
我喜欢用python进行探索,最近我看了Matrix,所以我想尝试一下。
假设我要这样做:
1 2 3 | While True: print ("010101010101010101") print ("101010101010101010") |
如果你运行它,它会继续打印直到你中止它。你还会看到这些数字混合在一起,因为它们会变快。
我并不是要求它每隔一秒左右就运行一次,我只是希望它稍微慢一点。有人能告诉我运行什么程序吗?
这将一个字符一个字符地打印一个字符串,它还将模拟在0.1到0.2秒的每个字符之间等待随机时间的打印:
1 2 3 4 5 6 7 8 9 10 | import random import time import sys def slowprint(str): for letter in str: sys.stdout.write(letter) sys.stdout.flush() time.sleep(random.random() * 0.1 + 0.1) print '' |
然后像这样使用:
1 2 3 | while True: slowprint("010101010101010101") slowprint("101010101010101010") |
实际上很有趣。可能性是无限的:
1 2 3 4 | message ="all work and no play makes jack a dull boy" while True: print ' ' * random.randrange(15), # indent chaotically slowprint("".join(random.choice([c.upper(), c]) for c in message)) |
产量
1 2 3 4 5 6 7 | aLl wORk And nO PLAy maKEs JacK A DULL BoY ALl wOrK and No pLay MAkEs Jack A dULL BOY ALl WOrk and No PLaY maKes JAck a DuLL bOY all wOrk ANd no pLAY MAKes JacK a DULL bOy all Work and No plAY mAkES JACk a dulL bOY all WOrk ANd nO Play MAkEs JacK a duLL BOY alL WorK aND no plAY makeS jAcK A DULL boy |
1 2 3 4 5 6 7 8 | import string import time tab = string.maketrans("01","10") binx ="010101010101010101" while True: binx = binx.translate(tab) print binx time.sleep(0.2) |