【问题标题】:ValueError: invalid literal for int() with base 10:ValueError:int() 以 10 为底的无效文字:
【发布时间】:2017-11-17 07:17:48
【问题描述】:
    sp = int(input("the dp is $"))
    print(sp)
    while True: #make sure they only put number
        try:
            int(sp)
        except ValueError:
            try:
                float(sp)
            except ValueError:
                print("This is not a number. Please put a valid price.")
        print("Please enter a valid number")
    #This is to ensure that the customer is entering a valid variable, not too high or low
    if sp <=100: print("Your price is too low. Please enter a higher and valid price.")
    if sp >=10000: print("Your price is too high. Please enter a lower and valid price")

当我尝试输入过高或过低的数字时,消息错误会起作用,但如果我输入字母,程序会显示错误。

【问题讨论】:

  • 你得到了哪个错误,完整的回溯是什么?以及您如何到达最后两行:您的 while 循环无法结束。
  • 是的,因为您使用的是sp = int(input("the dp is $"),因此您的整个while True 循环毫无意义。删除对int 的调用,这就是循环和try-except 的用途!

标签: python valueerror


【解决方案1】:

缩进很重要。我想这就是你想要做的?此外,由于您的 input() 位于循环之外,因此当有人输入无效数字时,它将永远使用该无效数字循环。

while True: #make sure they only put number
    sp = int(input("the dp is $"))
    print(sp)
    try:
        int(sp)
    except ValueError:
        try:
            float(sp)
        except ValueError:
            print("This is not a number. Please put a valid price.")

    #This is to ensure that the customer is entering a valid variable, not too high or low
    if sp <=100: print("Your price is too low. Please enter a higher and valid price.")
    elif sp >=10000: print("Your price is too high. Please enter a lower and valid price")
    else: print("Success")

【讨论】:

    【解决方案2】:
    sp = int(input("the dp is $"))
    

    您已经在此处将变量定义为整数。

    没有错误信息我只能推测,但我认为它已经发生在这里,因为字符串无法转换为 int。

    【讨论】:

      猜你喜欢
      • 2018-03-26
      • 1970-01-01
      • 2021-07-23
      • 1970-01-01
      • 2021-01-10
      • 2020-10-12
      • 2021-01-09
      • 2016-01-22
      • 2021-08-06
      相关资源
      最近更新 更多