我尝试运行脚本时遇到此错误:
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
converter()
File "C:\Users\Joan\Documents\School\Computing\Coursework\A453 - Python\Currency Converter.py", line 19, in converter
exchange(currencyList)
File "C:\Users\Joan\Documents\School\Computing\Coursework\A453 - Python\Currency Converter.py", line 33, in exchange
crntItem = currencyList.index[crntCurrency] =+ 1
TypeError: 'builtin_function_or_method' object does not support item assignment
这是我的代码,一个未完成的货币转换器:
# Global ist
currencyList = ["Pound Sterling", 1, "Euro", 1.22, "US Dollar", 1.67, "Japanese Yen", 169.9480]
#################################
# A program to convert currency #
# Main function #
#################################
def converter():
currencyList = ["Pound Sterling", 1, "Euro", 1.22, "US Dollar", 1.67, "Japanese Yen", 169.9480]
print("1) Enter an amount to be exchanged.")
print("2) Change exchange rates.")
choice=0
while choice==0:
selected=int(input("Please select an option: "))
if selected == 1:
choice = 1
exchange(currencyList)
#################################
# Giving exchanged rate #
#################################
def exchange(currencyList):
crntAmnt = int(input("Please enter the amount of money to convert: "))
crntCurrency = ("Please enter the current currency: ")
newCurrency = ("Please enter the currency you would like to convert to: ")
listLength = len(currencyList)
crntItem = currencyList.index[crntCurrency] =+ 1
print(crntItem)
newItem = currencyList.index[newCurrency] =+ 1
print(newItem)
我尝试将主要功能设置为菜单,然后调用其他子功能来完成相关选择。我想知道这是否是一个好的方法来编码,因为我看到我的老师做了类似的事情,我应该把它放入'if'语句等。
这是一种好的,正确的编码方式吗?
答案 0 :(得分:2)
currencyList.index
是方法参考;要索引列表,请删除.index
部分:
crntItem = currencyList[crntCurrency]
print(crntItem)
newItem = currencyList[newCurrency]
我怀疑您正试图在列表中找到crntCurrency
的索引,然后添加1以找到该值:
crntItem = currencyList[currencyList.index(crntCurrency) + 1]
和
newItem = currencyList[currencyList.index(newCurrency) + 1]
但也许你应该在这里使用字典:
currencies = {"Pound Sterling": 1, "Euro": 1.22, "US Dollar": 1.67, "Japanese Yen": 169.9480}
这会将货币名称映射到一个数字,所以现在您只需查找货币而无需弄乱索引:
crntItem = currencies[crntCurrency]
哦,你忘记了实际的用户输入;在要求转换货币时添加input()
来电:
crntCurrency = input("Please enter the current currency: ")
newCurrency = input("Please enter the currency you would like to convert to: ")