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 which validates that the user input is a float before it takes an action on it.

#create a while loop to seek user input for fuel to burn in the next second until valid input is provided

#cast valid user input as a float

#use try and except statements to account for invalid user input
        
        while (some condition):
            x = (input("Enter a number: "))
            try:
                x = float(x)
                break
            except ValueError as e:
                print(str(x) + " is not a valid number.  Please try again.")

3) Define a function that asks a user for input, does something if the answer is "yes", does something else if the answer is "no" and prompts the user again if the answer is neither "yes" or "no".

def user_input():
    while True:
        x = input("Enter yes or no: ")
        if (x == "yes" or x == "Yes"):
            continue
        elif (x == "no" or x == "No"):
            break
        else:
            print("Invalid input.  Please try again.")
 

user_input()

4) Similar to #3 except that the function has a parameter.

def user_input(x):
    while True:
        x = input("Enter y or n: ")
        if (x == "y" or x == "Y"):
            continue
        elif (x == "n" or x == "N"):
            break
        else:
            print("Invalid input.  Please try again.")

user_input("Enter y or n")




Comments

  1. AI & ML in Dubai
    https://www.nsreem.com/ourservices/ai-ml/
    Artificial intelligence is very widespread today. In at least certainly considered one among its various forms has had an impact on all major industries in the world today, NSREEM is #1 AI & ML Service Provider in Dubai
    1633169360127-11

    ReplyDelete
  2. Lovely blog, to know more about Data Science do check this info graphic by Mizoram University https://bit.ly/3GvHatD

    ReplyDelete

Post a Comment

Popular posts from this blog

AI, ML, NN and DL: a visual explanation

Understanding And Interpreting Gain And Lift Charts

Creating a time series forecast using IBM SPSS Modeler