'How to break out of a while loop with the press of a specific button in Python?

I am trying to build a simple game where the user is asked to press 'P' to start, and it will start generating different patterns until the user presses 'S'. Obviously what I have doesn't work, but I am not sure what to do at this point.

while ans == 'p' or ans == 'P':

    function1()
    function2()
    function3()

    if ans == 's' or ans == 'S':
        break

I have seen solutions where keyboard.is_pressed() is used but is there a way to do this without using any pre-defined function?

Thanks!



Sources

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

Source: Stack Overflow

Solution Source