python read keyboard input code example

Example 1: how to receive user input in python

var = input("Text: ")

Example 2: python listen to keyboard input

# For windows
from pynput import keyboard

def on_press(key):
    try:
        k = key.char  # single-char keys
    except:
        k = key.name  # other keys
    print('Key pressed: ' + k)
    return False  # stop listener; remove this if want more keys

listener = keyboard.Listener(on_press=on_press)
listener.start()  # start to listen on a separate thread
listener.join()  # remove if main thread is polling self.keys

Example 3: python keyboard input

# To get input from the user in python:

x = input("Optional prompt for input here")

Example 4: python user input

user = input("yes, no\n")