阻止用户在 Python 3 中输入字符串
Preventing a user from entering a string in Python 3
我在Python 3中写了这个,但是如何防止用户输入字符串?
x = int(input("If you want to play with computer, click 0. If you want to play with your friend, click 1. "))
你可以在整数转换之前用str
类型的isnumeric
方法添加一个if语句,像这样:
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.')
使用 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")
我在Python 3中写了这个,但是如何防止用户输入字符串?
x = int(input("If you want to play with computer, click 0. If you want to play with your friend, click 1. "))
你可以在整数转换之前用str
类型的isnumeric
方法添加一个if语句,像这样:
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.')
使用 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")