Posts

Showing posts from January, 2021

Python script for requesting user input repeatedly

 Someone recently asked how to write a Python script that took user input into account and took some action based on the validity of the user input.  Here are some code snippets that I developed for a few different scenarios: 1) A game is being played and it has just ended.  How would you ask the user if they wanted to play again? game_running = True #assuming the game is running play_again = input("Play again? ")  #get user input while True: #restart game if answer is "y" or "Y"         if play_again == 'y' or play_again == "Y":             game_running = True             break         else: #print thank you message and exit the program             print("Thank you for playing!")             game_running = False             break Here if the user answers either "y" or "Y", they get to play the game again.  If they type anything else, they receive a thank you message and the game ends. 2) Create a while loop