Search code examples
pythoninputwhitelistblacklist

Preventing a user from entering a string in Python 3


I wrote this in Python 3, but how can I prevent the user from entering a string?

x = int(input("If you want to play with computer, click 0. If you want to play with your friend, click 1. "))

Solution

  • using try/except

    while True:
        user_input = input("If you want to play with computer, click 0. If you want to play with your friend, click 1. ")
        try:
            user_input = int(user_input)
            # do something
            break
        except ValueError:
            print("input a valid choice please")