如何将Python函数careers存入变量后续使用?多print语句函数如何用return获取指定格式返回值
Great question! Let's break this down step by step to fix the None issue and get your function working the way you want.
First, let's clarify why you're seeing None:
- Your original
careers()function usesprint()to output text directly, but it doesn’t have areturnstatement. In Python, any function without an explicitreturnautomatically returnsNonewhen it finishes running. - When you run
post = careers(), you’re assigning thatNonevalue topost. Trying to callpost()later would throw an error (sinceNoneisn’t a function), and printingpostdirectly would just showNone.
Fix 1: Modify the Function to Return the Formatted String
Instead of printing each line immediately, we’ll build a single string that matches your desired output, then return that string. This lets you capture the full text in a variable and reuse it however you want.
Here’s the updated code:
jobs = ('Cook', 'Vet', 'Doctor', 'Pilot') def careers(): # Start with the first line plus a blank line output = "Heres a list of jobs\n\n" # Add each job line to the output for j in jobs: output += f"This person is a {j}.\n" # Add the final line with a preceding blank line output += "\nAre you interested in any of these as careers?" return output
Fix 2: Store the Function’s Output in a Variable
Now when you call careers(), it returns the full formatted string instead of printing it. Save this to a variable like so:
post = careers()
Use the Variable
To print the text in your exact desired format:
print(post)This will output:
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?
You can also reuse the
postvariable for other tasks, like writing to a file:with open("career_options.txt", "w") as f: f.write(post)
Alternative: Cleaner String Building with a List
If you prefer a more scalable approach (especially if you plan to add more lines later), collect lines in a list then join them with newlines:
jobs = ('Cook', 'Vet', 'Doctor', 'Pilot') def careers(): lines = [ "Heres a list of jobs", "", # Blank line ] for j in jobs: lines.append(f"This person is a {j}.") lines.extend(["", "Are you interested in any of these as careers?"]) return "\n".join(lines)
This produces the same output but is easier to modify as your needs change.
内容的提问来源于stack exchange,提问作者curtcab

