简体   繁体   中英

While loop waiting for input python

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?

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/

您可以使用curses.Excel优秀的文档在这里: http ://docs.python.org/dev/howto/curses.html#user-input

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM