我正在编写一个程序,允许用户从菜单中选择选项,并在此基础上,所选选项的详细信息将被打印出来。我需要把数量和价格相乘才能得到成本。问题是,我的价格和数量都在嵌套字典里。如果用户选择选项1>;3AB,它应该根据3AB的数量和价格打印成本。我该怎么做
stock = {
'3AB': {'Name': 'Telcom', 'Purchase Date': '12/12/2018', 'Price': '1.55', 'Volume':'3000'},
'S12': {'Name': 'S&P', 'Purchase Date': '12/08/2018', 'Price': '3.25', 'Volume': '2000'},
'AE1': {'Name': 'A ENG', 'Purchase Date': '04/03/2018', 'Price': '1.45', 'Volume': '5000'}
}
def menu():
menuChoice =True
while menuChoice:
print ("""
Menu
1. List Holding and Sold details for a Stock
2. Buy Stock
3. Sell Stock
4. list Holdings
5. list Sold Stock
0. Exit
""")
menuChoice= input("Enter Choice: ")
if menuChoice=="1":
option1()
elif menuChoice=="2":
print("\n Buy Stock")
elif menuChoice=="3":
print("\n Sell Stock")
elif menuChoice=="4":
print("\n List Holdings")
elif menuChoice=="5":
print("\n List Sold Stock")
elif menuChoice=="0":
break
elif menuChoice !="":
print("\n Invalid. Please Re-enter choice: ")
def option1():
input1 = input("Please enter code: ").lower()
test = stock['3AB']['Volume'] * stock['3AB']['Price']
print(test)
if input1.upper() == "3AB":
print("\nCode: " + input1.upper())
print("Name: " + stock['3AB']['Name'])
print("Last Purchase Date: " + stock['3AB']['Purchase Date'])
print("Average Price: " + stock['3AB']['Price'])
print("Volume: " + stock['3AB']['Volume'])
print("Investment Cost ($): " + ())
elif input1.upper() == "S12":
print("\nCode: " + input1.upper())
print("Name: " + stock['S12']['Name'])
print("Last Purchase Date: " + stock['S12']['Purchase Date'])
print("Average Price: " + stock['S12']['Price'])
print("Volume: " + stock['S12']['Volume'])
elif input1.upper() == "AE1":
print("\nCode: " + input1.upper())
print("Name: " + stock['AE1']['Name'])
print("Last Purchase Date: " + stock['AE1']['Purchase Date'])
print("Average Price: " + stock['AE1']['Price'])
print("Volume: " + stock['AE1']['Volume'])
else:
print("Stock is not found in your portfolio.")
print(input("Enter another option: "))
menu()
你需要的是数字而不是字符串。您还可以使用字典来调用函数,而不是使用大型if-elif构造,从而使代码成为“snappier”。使用函数请求数字/输入也是减少重复编码的一个好方法(干-不要重复自己):
在dict中固定数字(或直接使用数字):
不要重复:
将函数映射到输入并调用它们:
一次运行的输出:
请参阅Why dict.get(key) instead of dict[key]?了解如何避免KeyError和string formating了解更多格式化选项
问题是在原始dict中将值存储为字符串。要解决此问题,只需将值转换为float:
或者不更改代码并将值存储为数字:
顺便说一句,你的代码在下一行仍然有一个问题。必须定义要打印的值:
相关问题 更多 >
编程相关推荐