2013-10-19 312 views
-1

錯誤:名稱沒有定義錯誤的Python

Traceback (most recent call last): 
    File "C:/Python/CurrencyCoverter/currencyconverter.py", line 16, in <module> 
    if userChoice == "1": 
NameError: name 'userChoice' is not defined 

如果我嘗試運行我的貨幣轉換腳本,這裏是腳本(目前尚未完成):

def currencyConvert(): 

    userChoice = input("What do you want to convert? \n1.)USD > UK \n2.)USD > UK \n") 


if userChoice == "1":  
    userUSD = imput("ENTERAMOUNT") 

    UK = userUSD * 0.62 
    print ("USD", userUSD, "= ", UK, "UK") 



elif userChoice == "2": 
    print ("Choice = 2") 

else: 
    print ("Error, Please Choose Either Option 1 or 2") 
+1

請更正縮進。 – zero323

+0

您不能像這樣訪問本地函數變量。你需要讓你的函數返回一些東西(這是你的情況更好的解決方案),或者讓userChoice成爲全局的。 userUSD = imput(「ENTERAMOUNT」)可能也存在問題(你的意思是input()?如果你使用Python 3,那麼下一行也可能會給你帶來不希望的結果,因爲你會將字符串整數,所以你的行應該看起來像這樣:userUSD = float(input(「ENTER AMOUNT」))) – kren470

回答

1

首先,我希望縮進只是在這裏搞砸了,而不是在你的實際腳本中;否則,這應該是你的首要任務。

我認爲你誤解了一個函數的觀點。你正在定義這個函數來獲得輸入,然後丟棄它(因爲它沒有被返回)。此外,你永遠不會調用這個函數。

如果我是你,因爲函數基本上是一行代碼,我會完全刪除函數。

此外,您的else塊的內容使我相信腳本的整體形式已被破壞。我會做類似如下:

# I kept the function in this example because it is used twice. In your example, it was only used once, which is why I recommended removing it. 
def getChoice(): 
    return input("What do you want to convert? \n1.)USD > UK \n2.)USD > UK \n") 
userChoice = getChoice() 
while userChoice != "1" and userChoice != "2": # better yet, you could have a list of valid responses or even use a dictionary of response : callback 
    userChoice = getChoice() 
# Process input here 
+1

感謝您的兄弟。 – PixelPuppet

1

的問題是,你是試圖訪問userChoice,該功能僅在currencyConvert範圍內可用。

要解決該問題,請currencyConvert回報userChoice,然後訪問它像這樣:

userChoice = currencyConvert() 

換句話說,你的代碼應該是這樣的:

def currencyConvert(): 

    userChoice = input("What do you want to convert? \n1.)USD > UK \n2.)USD > UK \n") 

    # Return userChoice 
    return userChoice 

# Access userChoice (the return value of currencyConvert) 
userChoice = currencyConvert() 

if userChoice == "1":  
    userUSD = imput("ENTERAMOUNT") 

    UK = userUSD * 0.62 
    print ("USD", userUSD, "= ", UK, "UK") 

elif userChoice == "2": 
    print ("Choice = 2") 

else: 
    print ("Error, Please Choose Either Option 1 or 2") 
相關問題