2 回答

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超5個(gè)贊
使用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貢獻(xiàn)1772條經(jīng)驗(yàn) 獲得超8個(gè)贊
您可以在整數(shù)轉(zhuǎn)換之前添加一個(gè)帶有 typeisnumeric方法的if 語(yǔ)句,如下所示: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.')
添加回答
舉報(bào)