You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Python函数careers存入变量后续使用?多print语句函数如何用return获取指定格式返回值

How to Return Formatted Text from Your Function and Store It in a Variable

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 uses print() to output text directly, but it doesn’t have a return statement. In Python, any function without an explicit return automatically returns None when it finishes running.
  • When you run post = careers(), you’re assigning that None value to post. Trying to call post() later would throw an error (since None isn’t a function), and printing post directly would just show None.

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 post variable 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 17:52:50