x = int(input("If you want to play with computer, click 0. If you want to play with your friend, click 1. "))
萧十郎
浏览 143回答 2
2回答
慕后森
使用try/exceptwhile 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")
您可以在整数转换之前添加一个带有 typeisnumeric方法的if 语句,如下所示:strx = 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.')