Skip to content
Advertisement

output on sentence generator?

Sorry, this may be a simple thing but I am just learning and when I try to run an example program from my textbook of a sentence generator the output I get is:

<function sentence at 0x000002B0F7CBD160>

I should instead get a sentence and I’m not sure what the hexadecimal(?) means. I have been experimenting with different programs like Pycharm and VS Code and it seemed to be working a few days ago in Pycharm but after working in VS Code I keep getting this output in both programs.

The code from the textbook:

import random

articles = ("A", "The")
nouns = ("boy", "girl", "bat", "ball")
verbs = ("hit", "saw", "liked")
prepositions = ("with", "by")


def sentence():
    return nounPhrase() + " " + verbPhrase() + "."


def nounPhrase():
    return random.choice(articles) + " " + random.choice(nouns)


def prepositionalPhrase():
    return random.choice(prepositions) + " " + nounPhrase()


def verbPhrase():
    return random.choice(verbs) + " " + nounPhrase() + 
           " " + prepositionalPhrase()


def main():
    number = int(input("Enter the number of sentences: "))
    for count in range(number):
        print(sentence)

if __name__ == "__main__":
    main()

Advertisement

Answer

The hex is the id of the sentence object

When you print, you’re printing (probably) the memory address of the sentence function, rather than its output when you print(sentence) rather than print(sentence())


Also note that generator means something special in Python – it’s a function which builds the next result, rather than calculating them all at once. This can be more efficient when you do not know how many values from an iterable you need, or if each call is expensive and you want to process each result in turn (rather than waiting for every result to be ready and then processing them all afterwards)

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement