Python if语句issu

2024-09-30 20:38:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python的新手,在下面的函数中,我尝试做一些验证过程。在

def countUpToTen(counter):
    if type(counter) is not int or counter == None:
        print("Invalid parameter!")
    if counter > 10:
        print("Counter can not be greater than 10!")
        return False
    else:
        count = 1
        while (count <= counter):
           print 'The count is:', count
           count = count + 1
        print("Done counting !")

countUpToTen("0s")

但当我把它叫做countUpToTen("0s")时,它会打印Invalid parameter!和{},但我只希望是Invalid parameter!。我不知道它如何将字符串与second if语句中的数字进行比较。任何帮助都会得到赞赏的。在


Tags: 函数ifparameteris过程deftypecount
2条回答

打印第一条错误消息后,您没有退出该函数。在

在Python2中,您仍然可以比较字符串和整数,因为数字总是比其他任何东西都低(除了None),因此第二条if语句也匹配:

>>> '0s' > 10
True

Python3取消了对任意类型之间比较的支持,而将int与{}进行比较会引发异常。在

在这种情况下,您应该使用return在参数无效时提前退出函数:

^{pr2}$

注意,python测试类型的方法是使用isinstance()。您应该使用is身份测试来测试None,因为None是一个单例对象,但是这里的测试是多余的;如果counter是{},那么它也不是{}的实例。以下就足够了:

if not isinstance(counter, int):
    print("Invalid parameter!")
    return

与其提前返回,不如考虑在下一个测试中使用elif

if not isinstance(counter, int):
    print("Invalid parameter!")
elif counter > 10:
    print("Counter can not be greater than 10!")
else:
    # etc.

注意,您几乎可以肯定使用的是python2,因此使用了太多的括号。^Python 2中的{}是一个语句,而不是函数,使用括号无论如何会导致您试图打印元组:

>>> print('This is a tuple', 'with two values')
('This is a tuple', 'with two values')
>>> print 'This is just', 'two values'
This is just two values

您可能已经发现了这一点,因为您使用的是带有两个参数的print,并且在一个位置上已经没有圆括号了。在

while循环的测试也不需要使用括号:

while count <= counter:

不要手动使用while和递增count,只需使用for循环和range()

if not isinstance(counter, int):
    print "Invalid parameter!"
elif counter > 10:
    print "Counter can not be greater than 10!"
else:
    for count in range(1, counter + 1):
       print 'The count is:', count

后一个循环也可以写成:

for count in range(counter):
   print 'The count is:', count + 1

您可以稍微重写if/else语句,使其成为if/elif/else构造:

def countUpToTen(counter):
    if type(counter) is not int or counter == None:
        print("Invalid parameter!")
    elif counter > 10:
        print("Counter can not be greater than 10!")
        return False
    else:
        count = 1
        while (count <= counter):
            print 'The count is:', count
            count = count + 1
        print("Done counting !")

countUpToTen("0s")

这也会产生您期望的输出。在

相关问题 更多 >