I am doing a program of say digit in python using recursion and i want that if digit==0 return nothing.
Code:
# Q1
# Say digit
# i/p = 412 - o/p = four one two
list = ['zero','one','two','three','four','five','six','seven','eight','nine']
n=412
def say_digit(n, list):
if n==0:
return ''
digit = int(n % 10)
n = n / 10
say_digit(n, list)
print(list[digit], end=' ')
return ''
if __name__ == "__main__":
n=int(input("Enter Number: "))
ans = say_digit(n, list)
print(ans)
Output:
CodePudding user response:
Use // instead of /
i.e. n = n // 10
/ gives float and // gives int
CodePudding user response:
The code does a division by 10 at each iteration. But there's no guarantee this will reach 0. In Python3, it does a floating point division. You can get to 0 with integer division (using // instead of /).
Here's an updated version:
# Q1
# Say digit
# i/p = 412 - o/p = four one two
numbers = ['zero','one','two','three','four','five','six','seven','eight','nine']
n=412
def say_digit(n, numbers):
if n==0:
return ''
digit = int(n % 10)
n = n // 10
return say_digit(n, numbers) ' ' numbers[digit]
if __name__ == "__main__":
n=int(input("Enter Number: "))
ans = say_digit(n, numbers)
print(ans)
It also translates each digit in the words from list.
Ideally, one shouldn't shadow built-in names like 'list'. To avoid that, this version uses the name 'numbers'.

