0

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

2 Answers 2

2

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")
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.