int()不能使用显式base转换非字符串

时间:2015-04-13 15:19:50

标签: 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()无法使用显式基础

转换非字符串

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

  

'str'对象不可调用

3 个答案:

答案 0 :(得分:1)

您的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))

或者更好地使用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)

当然,在实际应用程序中,您将以某种方式处理“无效”用户输入。例如,使用适当的异常处理。但这是另一个故事...

答案 1 :(得分:1)

首先:你的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

答案 2 :(得分:0)

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

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