2016-11-06 117 views
1

這是我的編碼:int()函數的參數必須是字符串或數字,而不是「元組」

#Getting them to import their code: 
number = int(input("Enter 7 digit GTIN code to get eighth number : ")) 

#importing math for subtracting later: 
import math 

#Getting the numbers X3 & X1 and then adding them: 
def eight(total): 
    multiplier = [3, 1] 
    total = 0 
    for i, digit in enumerate(str(number)): 
     total = total + int(digit)*multiplier[i%2] 

#Subtracting the total to get the last number: 
     nearest_10 = int(math.ceil(total/10.0)) * 10 
     return nearest_10 - total 


code = number,eight(number) 
code = int(code) 
print(code) 

#printing their full number: 



#Checking the validity of the eight digit GTIN-8 code: 

def validity(valid): 
    multiplier = [3, 1] 
    valid = 0 
    string = "" 
    for i, digit in enumerate(list(str(code))): 
     valid = valid + str(digit)*multiplier[i%2] 
     string = string+str(str(digit)*multiplier[i%2])+", " 

    if code % 10 == 0: 
     print"Valid" 
    else: 
     print"Not valid" 

然而,當我想我的代碼轉換爲整數的後面,因爲它需要爲回答一個整數,它這樣說:

code = int(code) 
TypeError: int() 
argument must be a string or a number, not 'tuple' 
+0

我重新格式化了您的代碼以更好地適應此網站,但縮進似乎已關閉。請檢查。 –

+0

什麼是代碼=數字,八(數字)應該做什麼? –

+0

'code = number,eight(number)'現在'code'是元組包含2個值:'number'和'eight(number)'https://en.wikibooks.org/wiki/Python_Programming/Tuples –

回答

0

解決此問題的簡單方法是將數字連接爲一個字符串,然後對結果字符串執行int()。就像:

code = '%s%s' % (number,eight(number)) 
code = int(code) 
print(code) 
0

code = number,eight(number) code = int(code)

您在這裏創建一個元組。數字,八(數字)是一個元組。它有2個值,它怎麼能被轉換成int

1

你行

code = number,eight(number) 

使得代碼爲二進制元組,(number, eight(number))。 Python增加了圓括號並構成一個元組,因爲它經常在幕後進行,以允許更漂亮的代碼。你的下一行然後試圖採取這個,這是不被允許的int()

我不知道你想eight(number)什麼,但爲什麼你試圖採取int()這裏,因爲這兩個numbereight(number)似乎已經整數目前尚不清楚。你想用這條線做什麼?

+0

我試圖獲得7位數已輸入的單個號碼,包括從功能八(總數)創建的號碼。因此,我可以創建一個八位數的數字,例如除以十 – Ella05

1

我認爲其他答案是有道理的,但正如Rory Daulton指出的那樣,您似乎已經在使用整數了。爲了避免產生元組並保持整數,比如說 code = 10 * number + eight(number)

然後直接打印。

相關問題