Home > Software design >  Cannot get output for more than one user defined digit
Cannot get output for more than one user defined digit

Time:09-18

def main():

Need the code to ask the user a number and print out number in words digit by digit. Ex. Input: 473 Output: four seven three

numbers = ["zero","one","two","three","four","five","six","seven","eight","nine"]

n = eval(input('Please input a number: '))
print('You typed a number: ',n)
print('The number in words: ', numbers[n])

Cannot get code here to print out more than one digit. I have tried a few for loops and always get the error message with my index

main()

CodePudding user response:

Because your list has 10 items and it can not find index for example 324 so you should split your number into digits and try it for each digit.

numbers = ["zero","one","two","three","four","five","six","seven","eight","nine"]

n = int(input('Please input a number: '))
print('You typed a number: ',n)
print('The number in words: ', end="")
for char in str(n):
    print(numbers[int(char)], end=" ")
print()

CodePudding user response:

You are basically trying to access an eleent in an array(your array only have 10 elements, so works fine for n<=10) that doesn't exist. You need to extract the digits, and try for every digit.

CodePudding user response:

you can put numbers in a dictionary numbers = {'0': 'zero', '1': 'one', '2': 'two', etc...}

then loop throw the user's string:

for number in n: print(numbers[number] " ", end='')

CodePudding user response:

here is version that uses a list comprehension:

numbers = ["zero","one","two","three","four","five","six","seven","eight","nine"]
inp = input()
print(" ".join([numbers[int(dig)] for dig in inp]))
  • Related