While loop waiting for input python

岁酱吖の 提交于 2019-12-11 20:24:11

问题


I have a question about while loops in python. I want to make a program that performs a while loop in a certain time.I want to add the extra feature that while the program us running,a certain variable can be changed by pressing a random key.

   from time import sleep
   import time
   i=0
   a=0
   while i<10:
       i=i+1
       i=i+a
       a=a+1
       time.sleep(1)
      print i

I want to do it that the variable a can be reset to 0 by pressing any key.The loop should continue unchanged if no button is pressed.What command should i add?

Thanks Edit: I tried:

import pygame
from pygame.locals import *
import time

i=0
a=0
pygame.init()
while i<10:
    pygame.event.get()
    i=i+a
    print i
    keys = pygame.key.get_pressed()
    if keys[K_ESCAPE]:
               i=0
    i=i+1
    time.sleep(1)
 pygame.quit()

But now nothing happens when I press a button.What did i miss?


回答1:


What you need is a non-blocking input function

while i<10:
    keys = pygame.key.get_pressed()
    etc
    ...

pygame has all sorts of event stuff built in so doing all the hard work of threading yourself shouldn't be necessary.

If that doesn't work for you check this out: http://www.darkcoding.net/software/non-blocking-console-io-is-not-possible/




回答2:


You can use curses.Excellent doc is here: http://docs.python.org/dev/howto/curses.html#user-input



来源:https://stackoverflow.com/questions/13033820/while-loop-waiting-for-input-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!