我是用 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
提交
取消