Home > Mobile >  Multiple print statements in a return [duplicate]
Multiple print statements in a return [duplicate]

Time:10-09

How would I store the below function, careers, in a variable for later use?

jobs = ('Cook', 'Vet', 'Doctor', 'Pilot')
def careers():
    print("Heres a list of jobs\n")

    for j in jobs:
        print("This person is a "   j   ".")
    
    print("\nAre you interested in any of these as careers?")

post = careers()

When I attempt to print(post()) (the above variable I assigned the function to) the output is None. I understand I should be using return to output the results of a function but am having trouble finding out to use return in a function with multiple print statements that need to stay in below format.

Heres a list of jobs

This person is a Cook.
This person is a Vet.
This person is a Doctor.
This person is a Pilot.

Are you interested in any of these as careers?

CodePudding user response:

you need to understand the concept of "return" in python , if you want to get a variable from a funnction , you can return it from that function and you will get it when/whereever you call that function here is a fixed version of your code

jobs = ('Cook', 'Vet', 'Doctor', 'Pilot')
def careers():
    output_of_careers = ""
    output_of_careers  = output_of_careers  "Heres a list of jobs\n\n"
    for j in jobs:
        output_of_careers = output_of_careers  "This person is a "   j   ".\n"
    
    output_of_careers = output_of_careers  "\nAre you interested in any of these as careers?"
    return output_of_careers
post = careers()
print(post)

CodePudding user response:

Assuming you actually want to store the function careers, you need to assign the function careers (note the absence of brackets) to post, not the result of calling careers().

The reason you're getting None is that if you don't return anything from a function in Python, you get None (though I'm surprised you're not getting a TypeError instead by trying to call None()).

  • Related