'Execute python code indefinetly when key is pressed

I'm a bit new to python so I don't know exactly how to do this. I was trying to create a script that would help me automate doing tasks in a game. When I created this script, I got stuck on how to execute code whenever the key was pressed (I.e. when f is pressed, the line of code will execute). However, I keep running into the problem where the script would execute anyway without my input and would then die. I want my script to be running indefinitely until closed and respond to keyboard inputs. Thanks

import time
from pynput.keyboard import Controller
import pyautogui
import keyboard  # Dormant module

pykeyboard = Controller()


def right():  # This is the action I want to do
    time.sleep(1)
    pykeyboard.press('d')
    pyautogui.keyDown("space")
    time.sleep(3)
    pyautogui.keyUp("space")
    pykeyboard.release('d')


def left():
    time.sleep(1)
    pykeyboard.press('a')
    pyautogui.keyDown("space")
    time.sleep(3)
    pyautogui.keyUp("space")
    pykeyboard.release('a')


time.sleep(3)

if input == 'r':  # This listens to input
    left()  # This creates output

if input == 't':
    right()



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source