防止用户在 Python 3 中输入字符串

我是用 Python 3 写的,但是如何防止用户输入字符串呢?

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.')
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python