How do you take a users input as a float?

后端 未结 2 663
悲哀的现实
悲哀的现实 2020-12-22 14:20

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 = {}
  whi         


        
2条回答
  •  时光取名叫无心
    2020-12-22 14:39

    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: ')
    

提交回复
热议问题