Reputation: 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
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
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