如何将用户输入作为浮点数? [英] How do you take a users input as a float?
问题描述
我正在运行Python 2.7.10。我正在处理的程序中有以下代码块。
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()
它的作用是提示用户输入项目和价格,然后将所有这些存储为键/值对,然后将最终字典写入第二个文本文件。然而,在第5行,它似乎是唯一的输入类型,除了有一个字符串。我试图通过 float()包围 raw_input ,并尝试使额外的变量无济于事。我能够将raw_input包装在 int()中,它可以工作,所以它把我扔了。
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.
当我将第5行更改为库存[item] = float(raw_input('Price:'))时出现以下错误:
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:
我必须更改代码,以便当用户在第5行输入数值时,它会保存到字典而不是字符串(当前) ?
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)?
推荐答案
简短的回答是使用 float(raw_input( 'Price:'))
,但是编写一个方法来处理浮点数的输入可能会更好(并且在你得到你需要的东西之前重试)。
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.')
然后使用方法
inventory[item] = input_float('Price: ')
这篇关于如何将用户输入作为浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!