您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何在Python中将用户输入限制为仅整数

如何在Python中将用户输入限制为仅整数

您的代码将变为:

def Survey():

    print('1) Blue')
    print('2) Red')
    print('3) Yellow')

    while True:
        try:
            question = int(input('Out of these options\(1,2,3), which is your favourite?'))
            break
        except:
            print("That's not a valid option!")

    if question == 1:
        print('Nice!')
    elif question == 2:
        print('Cool')
    elif question == 3:
        print('Awesome!')
    else:
        print('That\'s not an option!')

它的工作方式是使循环无限循环,直到仅放入数字为止。因此,如果我输入“ 1”,它将破坏循环。但是如果我放“ Fooey!” 该except语句将捕获“将引发的错误” ,并且该循环将循环,因为它没有被破坏。

python 2022/1/1 18:35:23 有417人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶