在打印第一條錯誤消息後,您沒有退出該功能。
在Python 2,你仍然可以比較字符串和整數,用數字總是比什麼都重要(除None
)低,所以第二if
聲明還匹配:
>>> '0s' > 10
True
的Python 3摒棄支持任意類型之間的比較,並將int
與str
進行比較,而不是引發異常。
在這種情況下,你應該使用return
提前退出功能,當參數無效:
if type(counter) is not int or counter == None:
print("Invalid parameter!")
return
注意測試Python的方式爲一個類型是使用isinstance()
。您應該使用is
身份測試測試None
,因爲None
是單身對象,但測試在這裏是多餘的;如果counter
是None
它不是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
'if(type)(counter)...'分支後不返回,所以代碼繼續執行。 '或者計數器==無'是多餘的; None不是整數類型。 – 2014-09-23 16:28:49
注意:'not isinstance(counter,int)'優於'type(counter)不是int'。 – jonrsharpe 2014-09-23 16:30:48