错误:
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")
答案 0 :(得分: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")
换句话说,您的代码应如下所示:
{{1}}
答案 1 :(得分: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