2014-11-24 42 views
-1

我只是新編程和作業,我們不得不使用用戶輸入的數字作爲家庭作業的二進制轉換器。當我運行這段代碼,我得到了以下錯誤:Python 3.4.2 IDLE:定義'denaryInput'時出錯

if denaryInput < 0: 
NameError: name 'denaryInput' is not defined 

我不確定我在做什麼錯了,任何答案不勝感激。使用

代碼:

"""We are asking the user for a number""" 

def getNumber(): 
    denaryInput = int(input("Please enter a number between 0 and 255: ")) 

"""We are validating the number""" 

def validateNumber(): 
    if denaryInput < 0: 
     print("Error: Number is too small, try again!" + " \n") 
     return False 
    elif denaryInput > 255: 
     print("Error: Number is too big, please try again!" + " \n") 
     return False 
    else: 
     return True 

def binaryNumber(): 
    result = [] 
    for number in range(8): 
     bit = denaryInput % 2 
     result.append(bit) 
     denaryInput = denaryInput // 2 
    result.reverse() 
    str1 = "".join(str(x)for x in result) 
    print (str1 + " \n")  

"""Now telling the computer to run the code above and in what order of operations""" 

def mainProgram(): 
    answer = getNumber() 
    validNum = validateNumber() 
    Binary = binaryNumber() 
    print("The binary equlivent for that number is " + Binary + " \n") 

mainProgram() 
+0

這種變化只存在於getNumber函數的局部範圍內 – 2014-11-24 18:50:55

+0

感謝您的幫助,我現在已經開始工作了 – rskw00 2014-11-24 19:41:51

回答

0

您需要從getnumber函數傳遞denaryInput作爲呼叫的一部分。 validatenumber函數需要傳入一個值才能真正被驗證。這些在每個功能中應該是不同的名稱。 例如: -

def validateNumber(numIn): 
    if numIn < 0 

另外,你應該從getnumber功能

denaryInput = int(input("Please enter a number between 0 and 255: ")) 
if validateNumber(denaryInput): #returns true if number valid 
    Return denaryInput 

驗證號碼最後,二進制是一個關鍵字,不應該出現在你的主要功能。