Plutonian Fairy
Plutonian Fairy

Reputation: 103

How to do something till an input is detected in python3?

I want to execute a piece of code till the user enters an input(detects a random keypress), how do I do that in Python 3.x?

Here is the pseudo-code:

while input == False:
    print(x)

Upvotes: 2

Views: 185

Answers (2)

Carlo Zanocco
Carlo Zanocco

Reputation: 2019

You can do it like this:

try:
    while True:
        print("Running")
except KeyboardInterrupt:
    print("User pressed CTRL+c. Program terminated.")

The user just need to press Control+c.

Python provide the built-in exception KeyboardInterrupt to handle this.

To do it with any random key-press with pynput

import threading
from pynput.keyboard import Key, Listener

class MyClass():
    def __init__(self) -> None:
        self.user_press = False

    def RandomPress(self, key):
        self.user_press = True

    def MainProgram(self):
        while self.user_press == False:
            print("Running")
        print("Key pressed, program stop.")

    def Run(self):
        t1 = threading.Thread(target=self.MainProgram)
        t1.start()

        # Collect events until released
        with Listener(on_press=self.RandomPress) as listener:
            listener.join()

MyClass().Run()

Upvotes: 3

era_misa
era_misa

Reputation: 200

If you want to interact with users, you may follow the below way:

flag = input("please enter yes or no?")
if flag == "no":
    print(x)

Upvotes: 1

Related Questions