python - 如何同时检查输入是否为数字和范围? Python

标签 python python-3.x loops input

我想检查我的输入是否同时是数字和范围(1,3)并重复输入直到我得到满意的答案。 现在我以这种方式这样做,但代码并不干净和简单......有没有更好的方法来做到这一点? 也许用 while 循环?

def get_main_menu_choice():
    ask = True
    while ask:
        try:
            number = int(input('Chose an option from menu: '))
            while number not in range(1, 3):
                number = int(input('Please pick a number from the list: '))
            ask = False
        except: # just catch the exceptions you know!
            print('Enter a number from the list')
   return number

将不胜感激。

最佳答案

我想这样做最干净的方法是删除双循环。但是,如果您同时需要循环和错误处理,那么无论如何您最终都会得到一些复杂的代码。我个人会选择:

def get_main_menu_choice():
    while True:    
        try:
            number = int(input('Chose an option from menu: '))
            if 0 < number < 3:
                return number
        except (ValueError, TypeError):
            pass

关于python - 如何同时检查输入是否为数字和范围? Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45202238/

相关文章:

python - 我如何在Python中使用if/elif创建一个while循环而又没有语法错误

python - 指示参数应该是可变引用

python - for循环内递增变量

python-3.x - Python Matplotlib 到 smtplib

check_order 的 C 程序无法正常工作

php - 如何在 PHP 中按日期(今天、昨天、8 月 29 日、28 日等)对 SQL 中的 foreach 项目进行排序?

python - 如何在Win10/powershell上获取免费/开放的本地端口以进行ssh转发

python - 如何在 python 中拆分一串数学表达式?

python - 仅对某些方法应用 Flask MethodView 装饰器

javascript - 使用python获取空白电子邮件