我是用 Python 3 写的,但是如何防止用户输入字符串呢?x = int(input("If you want to play with computer, click 0. If you want to play with your friend, click 1. "))
2 回答
慕后森
TA贡献1802条经验 获得超5个赞
使用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")
料青山看我应如是
TA贡献1772条经验 获得超8个赞
您可以在整数转换之前添加一个带有 typeisnumeric方法的if 语句,如下所示:str
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.')
添加回答
举报
0/150
提交
取消