int()无法用显式bas转换非字符串

2024-05-21 02:10:01 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的代码:

import easygui
from random import randint

Minimum = easygui.enterbox(msg = "Choose your minimum number")
Maximum = easygui.enterbox(msg = "Choose your maximum number")
operator = easygui.enterbox(  msg="which operator would you like to use? X,/,+ or - ?",title="operator")
questions = easygui.enterbox(msg = "enter your desired amount of questions")

for a in range(int(questions)):
  rn1 = randint(int(Minimum), int(Maximum))
  rn2 = randint(int(Minimum), int(Maximum))
  answer = easygui.enterbox("%s %s %s =?" %(rn1, operator, rn2))
  realanswer = operator (int(rn1,rn2))
  if answer == realanswer:
   print "Correct"
  else:
   print 'Incorrect, the answer was' ,realanswer

当我尝试运行它时,所有的输入框都正常,当它看到第13行时,它会产生以下错误:

int() can't convert non-string with explicit base

我试着在没有int()的情况下运行代码,然后它给了我:

'str' object is not callable


Tags: 代码answeryourmsgoperatorintquestionsrandint
3条回答

第一:您的operator是一个字符串,而不是函数。你不能调用'/'(2,3),所以如果operator=='/',你仍然不能调用operator(2,3)

第二个:int(rn1), int(rn2)是如何将两个不同的数字转换为整数,而不是int(rn1, rn2)

第三:来自randint()的返回值已经是整数,不需要再次转换。


我建议在输入数字时将其转换为整数,只转换一次,而不是对每个引用都这样做。因此:

minimum = int(easygui.enterbox(msg="Choose your minimum number"))
maximum = int(easygui.enterbox(msg="Choose your maximum number"))
operator = easygui.enterbox(msg="which operator would you like to use? X,/,+ or - ?", title="operator")
questions = int(easygui.enterbox(msg="enter your desired amount of questions"))

# Select a function associated with the chosen operator
operators = {
    '*': lambda a,b: a*b,
    '/': lambda a,b: a/b,
    '+': lambda a,b: a+b,
    '-': lambda a,b: a-b,
}
operator_fn = operators.get(operator)
if operator_fn is None:
    raise Exception('Unknown operator %r' % operator)

for a in range(questions):
    rn1 = randint(minimum, maximum))
    rn2 = randint(minimum, maximum))
    answer = int(easygui.enterbox("%s %s %s = ?" % (rn1, operator, rn2)))
    realanswer = operator_fn(rn1,rn2)
    if answer == realanswer:
        print "Correct"
    else:
        print 'Incorrect, the answer was', realanswer

您的operator变量保存一个字符串。必须使用该字符串来确定要执行的实际操作。

像这样的:

if operator == "+":
      realanswer = rn1 + rn2
elif operator == "-":
      realanswer = rn1 - rn2
elif operator == "/":
      realanswer = rn1 / rn2
elif operator == "*":
      realanswer = rn1 * rn2
else
      raise Exception('Bad operator {}'.format(operator))

或者更好地使用^{} module

# top of your program
import operator

my_operators = { '+': operator.add,
                 '-': operator.sub,
                 '*': operator.mul,
                 '/': operator.div }

# ...
# and later:
realanswer = my_operators[operator](rn1,rn2)

当然,在实际的应用程序中,您可能需要处理“无效”的用户输入。例如,使用正确的异常处理。但这是另一个故事。。。

operator只是一个字符串,您仍然需要编写使它有意义的代码。你可以这样做:

if operator in ('+', 'add'):
    realanswer = rn1 + rn2
elif operator in ('-', 'subtract'):
    realanswer = rn1 - rn2
else:
    print operator, "is not valid"

相关问题 更多 >