【发布时间】:2020-07-11 11:03:50
【问题描述】:
我是在 Python 3 中编写的,但是如何防止用户输入字符串?
x = int(input("If you want to play with computer, click 0. If you want to play with your friend, click 1. "))
【问题讨论】:
标签: python input whitelist blacklist
我是在 Python 3 中编写的,但是如何防止用户输入字符串?
x = int(input("If you want to play with computer, click 0. If you want to play with your friend, click 1. "))
【问题讨论】:
标签: python input whitelist blacklist
使用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")
【讨论】:
您可以在整数转换之前添加带有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.')
【讨论】: