我是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语句中的数字进行比较。任何帮助都会得到赞赏的。在
打印第一条错误消息后,您没有退出该函数。在
在Python2中,您仍然可以比较字符串和整数,因为数字总是比其他任何东西都低(除了
None
),因此第二条if
语句也匹配:Python3取消了对任意类型之间比较的支持,而将}进行比较会引发异常。在
int
与{在这种情况下,您应该使用
^{pr2}$return
在参数无效时提前退出函数:注意,python测试类型的方法是使用},那么它也不是{}的实例。以下就足够了:
isinstance()
。您应该使用is
身份测试来测试None
,因为None
是一个单例对象,但是这里的测试是多余的;如果counter
是{与其提前返回,不如考虑在下一个测试中使用
elif
:注意,您几乎可以肯定使用的是python2,因此使用了太多的括号。^Python 2中的{}是一个语句,而不是函数,使用括号无论如何会导致您试图打印元组:
您可能已经发现了这一点,因为您使用的是带有两个参数的
print
,并且在一个位置上已经没有圆括号了。在对
while
循环的测试也不需要使用括号:不要手动使用
while
和递增count
,只需使用for
循环和range()
:后一个循环也可以写成:
您可以稍微重写if/else语句,使其成为if/elif/else构造:
这也会产生您期望的输出。在
相关问题 更多 >
编程相关推荐