Python如果语句问题

Python如果语句问题

问题描述:

我是新来的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!Counter can not be greater than 10!,但我想到刚Invalid parameter!。我不知道它是如何比较一个字符串与第二个if语句中的数字。任何帮助将被appriciated。

+0

'if(type)(counter)...'分支后不返回,所以代码继续执行。 '或者计数器==无'是多余的; None不是整数类型。 – 2014-09-23 16:28:49

+2

注意:'not isinstance(counter,int)'优于'type(counter)不是int'。 – jonrsharpe 2014-09-23 16:30:48

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

在Python 2,你仍然可以比较字符串和整数,用数字总是比什么都重要(除None)低,所以第二if声明还匹配:

>>> '0s' > 10 
True 

的Python 3摒弃支持任意类型之间的比较,并将intstr进行比较,而不是引发异常。

在这种情况下,你应该使用return提前退出功能,当参数无效:

if type(counter) is not int or counter == None: 
    print("Invalid parameter!") 
    return 

注意测试Python的方式为一个类型是使用isinstance()。您应该使用is身份测试测试None,因为None是单身对象,但测试在这里是多余的;如果counterNone它不是int或者的实例。以下就足够了:

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. 

注意,你几乎肯定是使用Python 2,因此使用过多的括号。 print在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

while count <= counter: 

,只需用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 
+0

除了'None',它不应该低于其他任何东西吗? – Yoel 2014-09-23 16:31:25

+0

@Yel:是的,CPython确实在所有其他事物之前排序了“没有”。当然,这些顺序都被归类为“实施细节”。 – 2014-09-23 16:32:49

你可以重写,如果稍有/ 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") 

这也会给你所期望的输出。