# Python easy understand solution

• Recursion will simplify the function.

``````def convertTo7(self, num):
if num < 0: return '-' + self.convertTo7(-num)
if num < 7: return str(num)
return self.convertTo7(num // 7) + str(num % 7)

``````

General iteration methode:

``````def convertTo7(self, num):
if num == 0: return '0'
n, res = abs(num), ''
while n:
res = str(n % 7) + res
n //= 7
return res if num > 0 else '-' + res``````

• You can use `divmod(num, 7)` in the method instead of using `\\` and `%`

``````        res = divmod(num,7)
return self.convertToBase7(res[0]) + str(res[1])
``````

• Javascript version:

``````var convertToBase7 = function(num) {
if( num < 0) {
return '-' + convertToBase7(-num);
}
if(num < 7) return num + ""
return convertToBase7((num / 7)>>0) + "" + (num % 7)
};
``````

Golang version:

``````import "strconv"

func convertToBase7(num int) string {
if  num < 0 {
return "-" + convertToBase7(-num)
}
if num < 7 {
return strconv.Itoa(num)
}
return convertToBase7((num / 7)) + "" + strconv.Itoa(num % 7)
}
``````

• @StefanPochmann advantage: `num, res = divmod(num, 7)`, disadvantage: `res = divmod(num,7)`

• @lanjiann But what's the advantage?

• `return res if num >= 0 else '-' + res`

`num` won't ever be equal to 0 at that point, you only need `>` in the comparison

• @tanoabeleyra I agree.

• I wrote a relatively straightforward Python snippet - but it is returning some weird values - when I run the code here. Basically I see return values prepended with zeroes

It works perfectly fine on my local python instance. Any ideas what I am missing here?
"""
arr = ""