Home > Software engineering >  Is there a way to translate this 'while' loop into a 'for' loop in python?
Is there a way to translate this 'while' loop into a 'for' loop in python?

Time:03-06

I have a decimal-to-any base converter as shown below:

import string
digs = string.digits   string.ascii_letters

def int2base(x, base):
    if x < 0:
        sign = -1
    elif x == 0:
        return digs[0]
    else:
        sign = 1

    x *= sign
    digits = []
    
    while x:
        digits.append(digs[x % base])
        x = x // base
    if sign < 0:
        digits.append('-')
    digits.reverse()
    return ''.join(digits)

print(int2base(51363,64))

... And I want to replace the while loop here with a for loop but I've tried and failed to do so. Help is apreciated (•‿•)

CodePudding user response:

Silly answer to a silly question :-)

Instead of

while x:

you could do:

for _ in iter(lambda: x, 0):

CodePudding user response:

But why do you want to use for loop? I think that FOR loop works with an iterable object (like range, List, Tuple, ...) in Python. You need to check an contition (x != 0). So, you have to use WHILE loop.

  • Related