I have made this function that is meant to print each digit of a number one-by-one without using loops (comprehensions are not included).I have done a good job thus far the only thing im missing is that my return statement completely ommits the number 0 (ex.print_digits(2019) = 2 1 9)
def print_digits(x):
ver = [u for u in str(x)]
if x < 10:
print(x)
else:
print(ver[0])
ver.pop(0)
a_string = "".join(ver)
inter = int(a_string)
return print_digits(inter)
CodePudding user response:
After
ver.pop(0)
a_string = '019'
, so
inter = int(a_string)
evaluates to 19
.
You can still print 0 by adding
if a_string[0] == '0':
print(0)
between
a_string = "".join(ver)
and
inter = int(a_string)
CodePudding user response:
Modified version
def print_digits(x):
ver = [u for u in str(x)]
# change 'x' to 'int' before comparison
if int(x) < 10:
print(x)
else:
ver.pop(0)
a_string = "".join(ver)
# comment this line. Now the function argument can be string.
# inter = int(a_string)
# give 'a_string' (instead of 'inter') to the function
return print_digits(a_string)
print_digits(2019)
CodePudding user response:
It was happening because when the number "09" gets converted to integer it changes to 9 and when the condition x<10 gets checked it turns out to be true. I have fixed your code.
def print_digits(x):
ver = [u for u in str(x)]
if int(x) < 10 and x[0]!="0":
print(x)
else:
print(ver[0])
ver.pop(0)
a_string = "".join(ver)
return print_digits(a_string)
CodePudding user response:
You could avoid recursion altogether using something like:
def print_digits(x):
print("\n".join(list(str(x))))