Search code examples
pythondictionarynumbersconverterswords

Python: Convert numbers to words


Hello everyone I'm trying to produce a code that will convert a number to a word in a given dictionary. But it seems to not print anything at all. no errors or anything. I tried many things to find the problem, still nothing.

When I enter 6 the program kicks back nothing.

It should output [six].

I thought it was a spacing problem but I dont think that is the case.

Here's what I have

import string


value = input("Enter a number 1 - 9 separted by commas: ")

def user_input(value):
    numbers = {}
    user_list = value.split(',')
    numbers = [(x.strip()) for x in user_list]
    return numbers
    print(numbers)

user_input(value)

numbers = user_input()

unit_number = {0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 
           5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine'}

def convert_n_to_w(numbers):
    i = len(str(numbers))

    if i == 0:
        return

    if i == 1:
        return unit_number[numbers]

    print(unit_number[numbers])

convert_n_to_w(numbers)

Can anyone please show me what I did doing wrong?

Update!!!!!!!

I added convert_n_to_w(numbers) and telling me

line 38, in <module> convert_n_to_w(numbers)

NameError: name 'numbers' is not defined

When I thought I defined it.


Solution

  • There are several problems with your code. I would like to modify you code. The code below can work well but not pythonic.

    value = input("Enter a number 1 - 9 separted by commas: ")
    
    def user_input(value):
        if isinstance(value, tuple):
            return list(value)
        else:
            user_list = value.split(',')
            numbers = [(x.strip()) for x in user_list]
            return numbers
    
    
    unit_number = {0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 
               5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine'}
    
    def convert_n_to_w(numbers):
        for n in numbers:
            print(unit_number[int(n)])
    
    numbers = user_input(value)
    
    convert_n_to_w(numbers)