在python中允许0到100之间的数字

时间:2014-05-06 14:10:33

标签: python

到目前为止,我有这段编码。我试图只允许0到100之间的数字。

并输入错误处理程序(Messagebox)

#This function will let the user at to the list
def add():
        try:
            value = int(ent1.get())
            mark.set(value)
            exammarks.append(value)
            lst1.insert(len(exammarks),value)
        except:

有人帮忙吗?

3 个答案:

答案 0 :(得分:1)

在python中,你可以把它写成常规的数学表达式:

foo = 50
if 0 <= foo <= 100:
    print "yup"

或者,使用try-except(这可以通过几种不同的方式完成):

foo = 101
try:
    if 0 <= foo <= 100:
        print "yup"
    else:
        raise ValueError, 'The number must be in the range 0-100'
except ValueError, e:
    print e

答案 1 :(得分:1)

如何使用内置的assert关键字?

def add():
    try:
        value = int(ent1.get())
        assert 0 <= value <= 100
        # continue processing
    except AssertionError:
        # handle exception as you wish
        pass

答案 2 :(得分:0)

>>> my_range = range(0,100)
>>> 10 in my_range
True
>>> 101 in my_range
False
>>> 
相关问题