2016-11-21 28 views
0
def converter(): 
    print ("Welcome to Andy's decimal to binary converter!") 
    x = raw_input("Enter an integer or enter 'exit' to exit program:") 

    if x=="exit": 
     print "Goodbye" 
     exit() 

    string = "" 

    while x!=0: 
     remainder =x%2 
     string =string+str(remainder) #giving error here and dont know why! 
     x =x/2 
    y =string 
    binary =y[::-1] 
    print "The integer in binary is: ",binary 

    again =raw_input("Would you like to enter another integer? Enter yes or no: ") 


    if again=="no": 
     print "Goodbye" 
     exit() 
    elif again=="yes": 
     return converter() 
    else: 
     print "Enter either 'yes' or 'no'" 

print converter() 
+0

這是你的全部代碼?什麼是導致錯誤的線? – elethan

+0

可以想象,如果'x'是非數字的,'x%2'可以做到這一點。如果它是一個字符串(並且,給定'raw_input',它*將*爲一個字符串),那麼我們會將它視爲格式字符串 –

+0

您的錯誤在這裏:'remaining = x%2'。 'x'是一個字符串,你試圖把它當作一個整數。在while循環之前,使'x'爲整數。 'x = int(x)'。 –

回答

1

您的代碼的問題在於它試圖對字符串進行數學運算。

remainder = x%2 

這被視爲"123" % (2),由於該字符串不包含有效的字符來代替你得到這個錯誤。

要解決這個問題,我會建議您在檢查值是否「退出」後將輸入轉換爲整數。請參閱:

if x=="exit": 
    print "Goodbye" 
    exit() 
else: 
    try: 
    x = int(x) 
    except: 
    print "%s is not a number!" % (x) 
    return converter() 

這裏我們使用一個嘗試,除了語句來處理,如果他們的投入是不是一個數字。

相關問題