Typeerror: not all Arguments converted During string formatting

Asked

Viewed 238 times

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, where the next error appears:

while (a % b != 0 ):
Typeerror: not all Arguments converted During string formatting

what I must change ?

1 answer

0

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

Test the type of parameters at the start 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   

Browser other questions tagged

You are not signed in. Login or sign up in order to post.