【问题标题】:ValueError with input and trying to convert input value into intValueError 输入并尝试将输入值转换为 int
【发布时间】:2018-11-12 01:56:47
【问题描述】:

我是初学者,请多多包涵。我正在尝试解决一个非常简单的问题,但是在输入和 int 命令中遇到了一致的错误。我要解决的问题如下:

您有 5 万欧元的债务。您比较不同的存款,最赚钱的存款是年复利 6% 的存款。你应该多少钱 投资该存款以在 N 年内拥有 50k€?

我的代码是:

FV=50000   #future value of the deposit is 50,000 euros
I=0.06     #the interest rate of the deposit is 6%
N=input("number of months:")
N=int(N)
print(FV/(1+I)**N)
print("I should invest", FV/(1+I)**N, "euros to have", FV, " euros in", N, 
"months with interest", I)

但是内核在第三行(输入命令)之后停止运行和执行,当我手动按 Enter 获取换行符时,我得到一个 ValueError 代码,上面写着:

ValueError: int() 以 10 为底的无效文字:''

谁能告诉我为什么会出现这个错误?我在解决问题方面哪里错了?提前致谢。

【问题讨论】:

  • 输入一个数字然后回车会发生什么?只要按回车就会输入''
  • 有提示时输入数字。如果按不带数字的回车键,则会读取空字符串,这对于 int() 来说是无效的文字。
  • 我不明白你的问题,timgeb。我在内核中按 Enter 以获得换行符,因为内核在第三行代码之后停止执行,但我不知道要输入什么数字,因为我不知道 N 的值(月数) ,这是我要解决的问题的一部分......
  • 内核没有“停止”,它在等待你输入 N。你不是在求解 N 的值,这里提供了 N。您正在尝试使用需要提供的一些 N 值来解决初始投资。然而,当你按下回车键时,你只是给它一个空字符串,这会导致 int(N) 失败,因为它是 int('')

标签: python jupyter-notebook


【解决方案1】:

代码似乎运行良好。我将添加一些打印语句,这可能有助于使事情更清楚。看看这是否有帮助。

FV=50000   #future value of the deposit is 50,000 euros
I=0.06     #the interest rate of the deposit is 6%
print("I am a computer program, i am about to ask you for an input. please enter something and then press enter")
N=input("number of years:")
if N != '': #can be replaced with if N:
    print("you have entered-",N)
else:
    print("that is an empty string")
N=int(N)
print(FV/(1+I)**N)
print("I should invest", FV/(1+I)**N, "euros to have", FV, " euros in", N, 
"years with interest", I)

【讨论】:

  • 非常感谢帕里托什!我现在明白了,它起作用了......另外,N 应该是“年数”,而不是“月数”,因为利率是每年的,所以我改变了它。谢谢你,你的解释真的很有帮助!
  • 很高兴为您提供帮助。欢迎编程,不要害怕尝试各种东西,并且在卡住时使用大量的打印语句! :) @Madrid_datalady
  • @Madrid_datalady 如果问题已解决,请点击绿色复选标记接受答案,向 Paritosh 表示感谢。
猜你喜欢
  • 2014-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-09
  • 2016-02-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多