How do you take a users input as a float?

2019-01-29 14:54发布

问题:

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)?

回答1:

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).

def input_float(prompt):
    while True:
        try:
            return float(raw_input(prompt))
        except ValueError:
            print('That is not a valid number.')

then use the method

inventory[item] = input_float('Price: ')