I am working on a program that uses a recursive function to print the digits of a number in English (i.e. 456 would display "Four Five Six".) Right now I am beyond confused and I don't have much code to show for the hour and a half of work I've done. I'm not looking for anyone to write this program for me, just offer some assistance. In theory I know what needs to be done but I'm having a very difficult time translating that into code.

def main:
    Number = raw_input("Please enter a number: ")
    return englishDigits

def convertEnglish(Number): 
    numEnglish = {0: "Zero", 1: "One", 2: "Two", 3: "Three", 4: "Four",
                  5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine"}

def englishDigits(Number): 
    digit = Number % 10
    digit = numEnglish.get(

Note that the code isn't even complete. I'm so stuck and obviously realize it doesn't run.

Recommended Answers

All 8 Replies

First of all let's deal with the ConvertEnglish() function:
The argument will probably be an int ('Number'), and it seems like you just need to return

numEnglish[Number]

As for the englishDigits() function:
You're first step is right - you should isolate the rightmost digit.
The second step however should pass that digit to the previous function.

Last but not least: you're main function needs to properly call the needed function.
Have a look here for more info on how to use functions in python: http://net.tutsplus.com/tutorials/python-tutorials/python-from-scratch-functions-and-modules-2/

Also remember that nothing will be executed if main() itself isn't called...

Good luck.

commented: Nice advice +13

here is my updated code... still struggling.

def main():
    List = createList()
    print(displayEnglishDigits)
    
def getNumber(prompt):
    try:
        number = input(prompt)
        number = eval(number)
        if type(number) == type(0) or type(number) == type(0.0):
            if number != "":
                return number
            else:
                return None
    except NameError:
        print("\nYou did not enter a number. Try again.")
    except SyntaxError:
        print("\nYou did not enter a number. Try again.")
    except:
        print("\nAn exception occured. Try again.")

def createList():
    #Create a blank list
    newList = []
    item = getNumber("Enter a list of numbers (<Enter> to quit): ")
    while item != None:
        #Add user input to the end of the created list
        newList.append(item)
        item = getNumber("Enter a list of numbers (<Enter> to quit): ")
    return newList


def displayEnglishDigits(List): 
    numEnglish = {0: "Zero", 1: "One", 2: "Two", 3: "Three", 4: "Four",
                  5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine"}
    digit = numEnglish[Number % 10]
    return displayEnglishDigits(number//10) + digit

You do not need createList, use Python naming convention: lower case with _ connected words for variables, UpperCasedWords for classes.

check about divmod function and pass integer number in your function. Forget float numbers at least first for simplicity:

def get_number(prompt):
    while True:
        try:
            number = int(raw_input(prompt))
        except ValueError as e:
            print("%s\nYou did not enter an integer number. Try again." % e)
        else:
            return number

Important test case for your function is 0 --> 'Zero'.

You don't need functions for something this simple:

num_english = {0: "Zero", 1: "One", 2: "Two", 3: "Three", 4: "Four",
                  5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine"}

for num in [0, 5]:
   print num, num_english[num]

So now, all you have to do it iterate over the numbers. You should not use code (like dictionaries) without understanding it first.

What do you mean I don't need functions? I need to obtain multiple values from the user, arrange them in a list, run through each item and determine the english version of their digits while using a recursive function.

You don't need the separate funcion "displayEnglishDigits(List)"; just put the lookup and print in "englishDigits(Number)". Although "englishDigits" will probably receive a list, not a number, since it has to delete the number printed, and send the remaining digits on through the recursive calls.

def recursive_print(list_in):
    """ this is not a solution to your homework but an example of using a
        print statement within a recursive function
    """
    if len(list_in):
        print list_in[0]          ## print before the function calls itself
        recursive_print(list_in[1:])
        print ".....", list_in[0] ## print after the function calls itself

    ## no items in list so just return without any more calls
    ## this is not required as the function would return without this but
    ## it makes the code more readable IMHO
    else:
        return

test_list = range(7)
print test_list, "\n"
recursive_print(test_list)

Also, you can use a list (which I hope you understand) instead of a dictionary, as the first item of a list is at zero offset-->"zero", the second item's offset is 1-->"one" (or you jump over this many items).

num_lit = ["zero", "one", "two"]    ## etc
num = 0
print num, num_lit[num]
num=2
print num, num_lit[num]

This is where I am right now. Still lost. I've been reading our book and it has not help me at all. I just don't know how it is possible to take a list of numbers, separate each digit in the number, and the display its corresponding english digit. so frustrated

numEnglish = {0: "Zero", 1: "One", 2: "Two", 3: "Three", 4: "Four",
              5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine"}

def main():
    #Create a list of digits to form the number
    number = createList()
    print("Digits: ", number)
    english = recursiveDisplay(number, numEnglish)
    print(english)
    
    print(recursiveDisplay(number, numEnglish))
    
def getNumber(prompt):
    badNumber = True
    #Loop while the value entered is not a valid number
    while badNumber:
        try:
            number = eval(input(prompt))
            if type(number) == type(0) or type(number) == type(0.0):
                badNumber = False
            else:
                print("\nYou did not enter a number. Try again.")
        except NameError:
            print("\nYou did not enter a number. Try again.")
        except SyntaxError:
            print("\nYou did not enter a number. Try again.")
        except:
            print("\nAn exception occured. Try again.")
    return number

def createList():
    newList = []
    n = eval(input("How many digits does the number have? "))
    for i in range(n):
        item = getNumber("Enter a digit: ")
        newList.append(item)
    return newList

def recursiveDisplay(number, numEnglish):
    #Base case for empty string
    if len(number) == 0:            
      return None
    #Take the first element
    first = int(number[0])
    #Look it up in the dictionary 
    english = numEnglish[first]
    #Display the english version
    return english
    #Recurse through rest of the list
    recursiveDisplay(number[1:])

You never enter at line 50, you must recurse in line 46 or 48 and join the results together.

For referrence (and as I do not want to give the ready solution to you), here is how you could do it without recursion:

num_english = {0: "Zero", 1: "One", 2: "Two", 3: "Three", 4: "Four",
                  5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine"}
def main():
    print(eng_words(get_number('Give integer number: ')))
    
def get_number(prompt):
    while True:
        try:
            number = int(raw_input(prompt))
        except ValueError as e:
            print("%s\nYou did not enter an integer number. Try again." % e)
        else:
            return number

def eng_words(number, number_words=num_english):
    return ' '.join(number_words[int(num)] for num in str(number))

main()
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.