I'm running Python 2.7.10. I have the following code block from a program I'm working on.
with open('inventory.txt', 'r+') as f:
inventory = {}
while True:
item = raw_input('Item: ')
inventory[item] = raw_input('Price: ')
if item == '':
del inventory['']
break
inv = str(inventory)
f.write(inv).rstrip()
print inventory
print inv
print f.read()
What it does is prompts a user for an item and price and then it stores all of those as key/value pairs and then writes that final dictionary onto a second text file. On line 5 however it seems like the only type of input it will except there is a string. I've tried to surround the raw_input by a float() and tried to make extra variables to no avail. I was able to wrap the raw_input in a int() and it work so it threw me off.
When I change line 5 to inventory[item] = float(raw_input('Price: ')) I get the following error:
File "C:\Users\Jarrall\Desktop\store\script.py", line 5, in <module>
inventory[item] = float(raw_input('Price: '))
ValueError: could not convert string to float:
What must I change about the code so that when a user enters a numerical value on line 5 it saves to the dictionary as such instead of a string (currently)?
The short answer is to use
float(raw_input('Price: '))
, but it might be better to write a method to handle the inputing of floats (and retry until you get what you need).then use the method