Rudolf Clausius
Rudolf Clausius

Reputation: 3

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. "))

Upvotes: 0

Views: 3838

Answers (2)

unil
unil

Reputation: 194

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")

Upvotes: 2

Tom Danilov
Tom Danilov

Reputation: 307

You can add an if statement with the isnumeric method of str type before the integer cast, like that:

x = input('Enter a number: ')

if x.isnumeric(): # Returns True if x is numeric, otherwise False.
    int(x) # Cast it and do what you want with it.
else: # x isn't numeric
    print('You broke the rules, only numeric is accepted.')

Upvotes: 2

Related Questions