如何将用户输入作为浮点数?

Jar*_*ett -3 python io input python-2.7

我正在运行Python 2.7.10.我正在处理的程序中有以下代码块.

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()
Run Code Online (Sandbox Code Playgroud)

它的作用是提示用户输入项目和价格,然后将所有这些存储为键/值对,然后将该最终字典写入第二个文本文件.然而,在第5行,它似乎是唯一的输入类型,除了有一个字符串.我试图用float()包围raw_input,并尝试使额外的变量无济于事.我能够将raw_input包装在一个int()中,它可以工作,所以它把我扔了.

当我将第5行更改为库存[item] = float(raw_input('Price:'))时,我收到以下错误:

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: 
Run Code Online (Sandbox Code Playgroud)

我必须对代码进行哪些更改,以便当用户在第5行输入数值时,它会保存到字典而不是字符串(当前)?

Cha*_* S. 5

简短的回答是使用float(raw_input('Price: ')),但最好是编写一个方法来处理浮点数的输入(并在你得到你需要的东西之前重试).

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

然后使用该方法

inventory[item] = input_float('Price: ')
Run Code Online (Sandbox Code Playgroud)

  • 你被低估的原因是因为这样的评论.如果你没有告诉我们你到底做了什么以及你得到了什么错误我们无法帮助你. (3认同)