2014-09-23 110 views
0

我是新來的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

回答

2

在打印第一條錯誤消息後,您沒有退出該功能。

在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

1

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

這也會給你所期望的輸出。