-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")
4

2 回答 2

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")
于 2013-10-19T16:58:10.073 回答
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
于 2013-10-19T17:06:15.957 回答