pythonpython-3.x

Trying to convert int to string without using in-built function in python 3


def int_to_str(num):
    is_negative = False
    if num:
        num, is_negative = -num, True
    s = []
    while True:
        s.append(chr(ord('0') + num % 10))
        num //= 10
        if num == 0:
            break
    return ('-' if is_negative else '') + ''.join(reversed(s))
num = input("Enter any numeric value: ")
print(int_to_str(num))    

Solution

  • If you have only an integer in the conditional of an if statement, the if statement will run if and only if the integer is not equal to zero. You need to do

    if num < 0:
    

    not

    if num:
    

    But indeed, @user8145959 has a point. The number inputted is already a string. When you pass the input string to int_to_str, it gets automatically converted to an integer at the places where you try integer operations on it.

    Edit: Automatic integer conversion works only in python 2, not python 3. My mistake.

    Edit2: Actually I'm just wrong. Didn't realize input() did the conversion already.