【问题标题】:How do you take a users input as a float?您如何将用户输入作为浮点数?
【发布时间】:2016-04-20 05:13:15
【问题描述】:

我正在运行 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()

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

当我将第 5 行更改为 inventory[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: 

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

【问题讨论】:

  • inventory[item] = float(raw_input('Price: '))
  • ^^^ 即便如此,使用浮点数来赚钱也是个坏主意。使用小数或整数
  • 正如我所说,我试过了。它给了我一个错误。请不要投反对票,因为这是一个初学者提出的严肃问题,你甚至没有回答我的问题,而且我没有多少声望点可以失去。 @BobDylan
  • @JarrallBarnett Bob 的评论是正确的,使用 float() 函数将其转换为浮点数。或者编写一个函数来接受来自输入的浮点数并使用它。
  • A) 我最初并没有对此投反对票(那个 DV 不是我的)。 B) 确实工作。问题一定是用户没有输入浮点数。手动铸造它并确保它实际上是一个浮点数是一种更好的方法。 C) 如果您在尝试执行此操作时收到错误,您还需要在此处显示错误,以便我们更好地帮助您。 D) 现在我将对此投反对票。

标签: python python-2.7 input io


【解决方案1】:

简短的回答是使用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.')

然后使用方法

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

【讨论】:

  • 您被否决的原因是因为这样的 cmets。如果您没有准确地告诉我们您做了什么以及您遇到了哪些错误,我们将无法帮助您。
【解决方案2】:

尝试使用我的代码。我刚刚成功并开始为那些人浏览网页。 免责声明:我是在 Python 3.7 中制作的,所以我不确定它是否能解决您的问题。

#Get Input
User_Input_Number_Here = input ("Enter a number: ")
try:
#Try to convert input to Integer
   User_Input_Converted_Here = int(User_Input_Number_Here)
#It worked, now do whatever you want with it
   print("The number is: ", User_Input_Converted_Here)
except ValueError:
#Can't convert into Integer
    try:
#Try converting into float
       User_Input_Converted_Here = float(User_Input_Number_Here)
#It worked, now do whatever you want with it
       print("The number is: ", User_Input_Converted_Here)
    except ValueError:
#Can't convert into float either. Conclusion: User is dumb
#Give custom error message
       print("Are you by any chance...\nRetarded?")

【讨论】:

    猜你喜欢
    • 2020-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-10
    • 2017-09-12
    • 2023-01-17
    相关资源
    最近更新 更多