2013-10-19 3 views
-1

오류 :이름 정의되지 않은 오류 파이썬

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()을 의미 했습니까?) 파이썬 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

문제는 당신이 있다는 것입니다 함수 외부에서 currencyConvert의 범위에서만 사용할 수있는 userChoice에 액세스하려고합니다.

이 문제를 해결 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") 
관련 문제