【问题标题】:How do you prevent the "ValueError: invalid literal for int() with base 10: '', with defined functions?你如何防止“ValueError:int()的无效文字,base 10:'',定义函数?
【发布时间】:2017-05-05 20:15:46
【问题描述】:

我正在尝试猜数字游戏。我试图让用户得到 3 次猜测,如果猜测太大,代码会说它太大,如果猜测太小,那么代码应该告诉他们,同时也允许如果他们的答案超出 1-10 的范围,他们重新输入他们的猜测,因为那是随机生成的数字的来源。我计划添加其他级别和排行榜,所以如果有人可以帮助我,我将不胜感激。这是我的代码:

import time
import random

answer1= ""
answer2= ""
answer3= ""

one= "You have two more guesses: "
two= "You only have one more guess. Be careful: "

number= random.randint(1,10)
number=str(number)

def code(a,number,b,n,d,e):
    a = int(a)
    number= int(number)
    if a > number and a <11:
        b=input("the number is too big. "+ n )
    elif a< number and a>-1:
        d= input("the number is too big. "+ n )
    elif a> 10 or a<0:
        e=input("please input a number smaller than 10 and bigger than 0: ") 


print(" -------------------- Guess the number game --------------------")
time.sleep(1)
answer= input("The aim of the game is to guess the number. Are you ready? (yes/no): ").lower()

if "yes" in answer:
    answer1=input("I am thinking of a number, between 0 and 10, What is the number: ")

    if answer1 == number:
        print ("Correct! Wow.. it only took you one guess")
        time.sleep(1)
        print("Come back again sometime...")
        time.sleep(1)
        print("BYE!")
        time.sleep(1)
        quit()


    elif answer1 != number:
        code(answer1,number,answer2,one,answer2,answer2)

    if answer2 == number:
        print ("Correct! it took you two turns.")
        time.sleep(1)
        print("Come back again sometime")
        time.sleep(1)
        print("BYE!")
        time.sleep(1)
        quit()


    elif answer2 != number:
        code(answer2,number,answer3,two,answer3,answer3)


    if answer3 == number:
        print ("Correct! Phew.... you guessed correctly in your last guess!")
        time.sleep(1)
        print("Come back again sometime")
        time.sleep(1)
        print("BYE!")
        time.sleep(1)
        quit()

    elif answer3 != number:
        print("Incorrect..... Sorry! ")
        time.sleep(1)
        print("The correct number was "+number)
        time.sleep(1)
        print("You lose! But don't stop trying!")
        time.sleep(1)
        quit()


elif "yes" != answer:
    print("That's too bad...")
    time.sleep(1)
    print("Come back when you're ready to....")
    time.sleep(2)
    print("LOSE!!")
    time.sleep(1)
    quit()

当我像这样使用它时,它一直给我:“ValueError:int() 的无效文字,基数为 10:'',当我这样使用它时(这是在 shell 中):

 ------------------- Guess the number game --------------------
The aim of the game is to guess the number. Are you ready? (yes/no): yes
I am thinking of a number, between 0 and 10, What is the number: 2
the number is too big. You have two more guesses: 1
Traceback (most recent call last):
  File "C:/Python33/Guweesss da numba.py", line 63, in <module>
    code(answer2,number,answer3,two,answer3,answer3)
  File "C:/Python33/Guweesss da numba.py", line 19, in code
    a = int(a)
ValueError: invalid literal for int() with base 10: ''

忽略代码的奇怪名称 - 我之前已经尝试过多次,所以没有使用任何名称。

【问题讨论】:

  • 当 answer1!= number 时,是预期的!
  • answer2 在顶部设置为 '' 并且从不重新分配。
  • 你可以试试a = int(a) if a else 0,这样空白输入就会被转换成0
  • 您应该研究循环(例如whilefor),这将大大简化您的代码。

标签: python


【解决方案1】:

你的问题是 python 没有像你想象的那样传递变量

def code(a,number,b,n,d,e):
    a = int(a)
    number= int(number)
    if a > number and a <11:
        b=input("the number is too big. "+ n )
    elif a< number and a>-1:
        d= input("the number is too big. "+ n )
    elif a> 10 or a<0:
        e=input("please input a number smaller than 10 and bigger than 0: ") 

无论您以bde 传递的内容在您执行e=input(...) 时都不会得到更新,因此当您完成时answer2 仍然是""。也没有理由将同一个变量传递 3 次。

你需要重做这个函数才能返回结果。

def code(a,number,n):
    a = int(a)
    number= int(number)
    if a > number and a <11:
        b=input("the number is too big. "+ n )
    elif a< number and a>-1:
        b= input("the number is too big. "+ n )
    elif a> 10 or a<0:
        b=input("please input a number smaller than 10 and bigger than 0: ") 
    return b

然后通过以下方式调用:

answer2 = code(answer1, number, one)

repl.it

一些进一步的说明:

  • 您可能希望按照其他人的建议添加输入错误检查
  • 对于太大和太小的猜测,您都说“数字太大”
  • 您可能需要查看一个循环,以便在不重新启动的情况下继续播放。
  • 我会推荐一个关于函数和传递变量的教程,因为这是根本问题。

【讨论】:

  • @User9123 似乎问了一些不同的问题,不是吗?
  • @rth 这是他的问题的根本原因。他可能还想为非整数用户输入添加错误处理,但这将修复黄金路径。仅添加整数错误处理将不会修复他的程序。
  • 同意,但我们应该调试代码还是回答问题?
  • @rth 如果有人问XY Problem,我倾向于认为您应该回答实际问题,而不是离题(或者在这种情况下,问题是更深层次问题的症状) .
  • 解决程序以便我可以对其进行逆向工程,本质上,如果您愿意,也会有所帮助。
【解决方案2】:

分析

您正在尝试将空字符串转换为整数。繁荣! 如果您真的想要这样的功能,请将所有三个猜测初始化为“-1”之类的值,这样这些值在语法上是合法的,但在语义上超出了范围。

改进检查

if a.isdigit():
    a = int(a)
else:
    print ("Don't be silly!  I need a number!")

建议

在测试之前不要编写太多代码。写几行,测试它们,直到他们做你想做的事才继续。在这里,您试图在 85 行代码中找出一个小错误。

了解函数的工作原理。您的code 函数接受六个参数,但忽略bde,覆盖输入的任何值。我认为您可能将那些与“可变”值混淆了,您可以更改这些值。调用程序不会收到分配的值。

使用有意义的变量名。

【讨论】:

    【解决方案3】:

    你可以捕捉到异常:

    try:
        a = int(a)
    exception ValueError as error:
        print(error)
        print('"{}" is not an integer'.format(a))
    

    【讨论】:

      【解决方案4】:

      您可能想尝试一种非常 Python 的方式来检查变量,方法是使用 try ... except 构造。所以改为 a = int(a) 是这样的:

      try:
        a = int(a)
      except:
        print ... something ...
      

      好吧,正如@TemporalWolf 指出的那样,功能存在很大问题。所以看看吧。 最后,您尝试获取数字并检查它,因此您可能需要一个循环,直到用户提供所需范围内的数字。它看起来像这样

      a=-1
      while 0<a<10:
        answer=input("I am thinking of a number, between 0 and 10, What is the number: ")
        try:
          a = int(answer)
        except:
          print "I need a number!"
          a = -1
          continue
        else:
          if a<1:
            print "number is negative"
            continue
          if a>10:
            print "number too big"
            continue
      

      这将保证您输入的内容正确,并且您有一个从 1 到 10 的数字。

      注意,@Prune 解决方案也非常好(老实说,我会使用它:)

      【讨论】:

        猜你喜欢
        • 2021-08-06
        • 2018-09-05
        • 2021-12-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-06-17
        • 2017-11-17
        • 2018-05-03
        相关资源
        最近更新 更多