2015-08-27 49 views
1

我對Python非常陌生。我在if語句中評估函數時遇到問題。一些非常簡單的代碼在這裏:檢查函數返回值時Python類型錯誤

import sys 
number = sys.argv 
def is_even(n): 
    if n%2==0: 
     return true 
    else: 
     return false 

if is_even(number): 
    print "The number is even" 
else: 
    print "The number is not even" 

當我嘗試和運行代碼我得到:

TypeError: unsupported operand type(s) for %: 'list' and 'int' 

不知道這是怎麼回事的。有人可以給我一些指點,說明我可能會做錯什麼嗎?

+1

您正在向函數傳遞一個列表('number'是一個列表,因爲'sys.argv'是一個列表),像'is_even(number [1])'一樣嘗試索引。 – Kamehameha

+0

sys。argv是類型列表,即使你只通過一個singel參數 –

回答

2

sys.argv是字符串列表。第一個字符串是腳本的名稱,所以你想要的是取第二個字符串並將其變爲int

import sys 

number = int(sys.argv[1]) # Changed this line 

def is_even(n): 
    if n%2==0: 
     return true 
    else: 
     return false 

if is_even(number): 
    print "The number is even" 
else: 
    print "The number is not even" 
+0

啊謝謝你!沒有想法argv這樣工作。謝謝 – KexAri

1

sys.argv是一個字符串列表,其中第一個元素是腳本路徑本身,之後的元素是您在命令行中傳遞給程序的參數。如果你想在命令行數傳,並把它在你的程序,你應該使用 -

number = int(sys.argv[1]) 

此外,你應該將其轉換爲int,如果你期待它作爲一個整數。


解釋 -

python <script.py> arg1 
     ^  ^
    sys.argv[0] sys.arv[1] ... 
1

您已通過number你的功能,sys.argv是傳遞給一個Python腳本,它的第一個項目是腳本的名稱和參數的其餘的命令行參數列表被傳遞到自定義參數腳本,所以在這種情況下,您需要將number[1]的整數傳遞給您的函數(如果您在命令行中傳遞了一個參數)。

sys.argv

The list of command line arguments passed to a Python script. argv[0] is the script name (it is operating system dependent whether this is a full pathname or not). If the command was executed using the -c command line option to the interpreter, argv[0] is set to the string '-c'. If no script name was passed to the Python interpreter, argv[0] is the empty string.

因此,你可以簡單地做:

import sys 
number = int(sys.argv[1]) 

def is_even(n): 
    if n%2==0: 
     return true 
    return false 

這並不是說,如果你想通過在命令行多個參數,你需要從第二個索引項結束:

numbers = map(int,sys.argv[1:]) 
1

當您致電sys.argv它返回一個列表,其中第一個元素是腳本名稱,其餘元素將是用戶通過輸入

修改:

import sys 
print sys.argv 
number = int(sys.argv[1]) 
def is_even(n): 
    if n%2==0: 
     return True 
    else: 
     return False 

if is_even(number): 
    print "The number is even" 
else: 
    print "The number is not even" 

輸出:

(Canopy 32bit) C:\Users\Desktop\yp_test>python sample.py 2 
['sample.py', '2'] 
The number is even 
1

我認爲你必須改變一行代碼中的

number = int(sys.argv[1]) 

然後它會奏效。

+0

不完全;如果你這樣做,你會得到'TypeError:並非在字符串格式化過程中轉換的所有參數,這可能會讓人困惑:P。你需要將它轉換爲一個'int'。 – Cyphase

+0

其實你的權利應該是number = int(sys.argv [1]) –