0
import time

i = 0
while True:
    i += 1
    time.sleep(0.2)
    print("i's value is " + str(i))
    input()

here is my code. So basicly i want to make this to count forever and when i type something is stops -breaks- the but instead it asks for an input for every loop. Is this even possible?

ohlr
  • 1,839
  • 1
  • 13
  • 29
  • You would have to use multithreading to do something like this. [Tutorial on Multithreading](https://www.tutorialspoint.com/python/python_multithreading.htm), [Official Documentation](https://docs.python.org/3/library/threading.html) One thread measures the time, the other get's the input. – ohlr Feb 20 '19 at 14:13

1 Answers1

0

You'll need to split your code into two threads, one which continuously prints and the other which listens for input. When the input listener receives an input it will need to send a message to the printing thread to stop.

import time
import threading

# Create printer function to print output
# make sure you add a lock so the printing doesn't go all funny
def printer(lock): 
    i = 0
    while True:
        i += 1
        time.sleep(0.2)
        with lock:
            print(f"i's value is {i}")

# create a thread lock to allow for printing
lock = threading.Lock()

# Create the thread to print
p = threading.Thread(target=printer, args=(lock,), daemon=True)

# start the thread
p.start()

# wait for input and when received stop the thread.
if input():
    p.join()
Jorick
  • 16
  • 2