TypeError: not all arguments converted during string formatting

1
def reduce(self,a,b):
   self.dividend =a
   self.divisor = b
   if(a != 0 and b != 0 ):
      if(a > b):
         self.dividend = a
         self.divisor = b
      else:
          self.dividendo = a
          self.divisor = b

      while(a % b != 0 ):
          r = a % b
          a = b
          b = r
      return b     

I have this part of the program, which then appears the following error:

  

while (a% b! = 0):
  TypeError: not all arguments converted during string formatting

What should I change?

    
asked by anonymous 29.04.2017 / 23:24

1 answer

0

This is because somewhere in your code the reduce function is being called with the parameter a being a string . In this case python interprets the % operator not as mod but as formatting operator .

Test the type of parameters at the beginning of the function.

def reduce (self, a, b):
    # validar os parametros
    try:
        a = int(a)
        b = int(b)
    except ValueError:
        if isinstance(a, int):
            erro = b
        else:
            erro = a
        raise ValueError('%s nao pode ser convertido em um numero' % erro)

    # valores validados prosseguir normalmente
    self.dividend = a
    self.divisor = b
    if(a != 0 and b != 0 ):
        if(a > b):
            self.dividend = a
            self.divisor = b
        else:
            self.dividendo = a
            self.divisor = b

    while(a % b != 0 ):
        r = a % b
        a = b
        b = r

    return b   
    
20.07.2017 / 19:31