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

如何将含for循环print语句的Python函数改为返回值形式?

问题描述

我是Python及编程领域的新手,正在通过freeCodeCamp学习并参加其认证考核。我需要编写一个接收对象列表作为参数的create_spend_chart函数,返回基于对象提款值生成的柱状图字符串。目前我编写的函数通过for循环中的print语句输出图表,但按考试要求调用print(create_spend_chart([...]))时,输出末尾会出现None——因为函数无返回值。现有代码如下:

def create_spend_chart(categories):
    withdrawals_name = []
    withdrawals_sum = 0
    for category in categories:
        withdrawals_sum += category.widthdrawal_tracker
        withdrawals_name.append([category.name, category.widthdrawal_tracker])

    for withdrawal in withdrawals_name:
        withdrawal.append(int((withdrawal[1]/withdrawals_sum) * 10) * 10)

    vals_to_be_evaluated = [a[2] for a in withdrawals_name]

    print('Percentage spent by category')

    for row in range(100, -10, -10):
        if row < 100 and row > 0:
            print(f" {row}|", ' '.join(
                ['o' if digit >= row else ' ' for digit in vals_to_be_evaluated]))
        elif row == 0:
            print(f"  {row}|", ' '.join(
                ['o' if digit >= row else ' ' for digit in vals_to_be_evaluated]))
        else:
            print(f"{row}|", ' '.join(
                ['o' if digit >= row else ' ' for digit in vals_to_be_evaluated]))
    print(' '*4 + '-'*(2*len(vals_to_be_evaluated)+1) + '-')

    str_val_eval = [a[0] for a in withdrawals_name]
    str_val = []
    spl_str = []

    for str_val_indv in str_val_eval:
        str_val.append(len(str_val_indv))
        spl_str.append([str_val_indv])

    max_str_val = max(str_val)

    for x in range(max_str_val):
        print(' '*5, end='')
        for y in spl_str:
            try:
                print(y[0][x], end=' ')
            except IndexError:
                print(' ', end=' ')
        print()

直接调用函数时输出正常,但用print(create_spend_chart([income_food, income_entertainment, income_business]))调用时,输出末尾会出现None。请问需要修改哪些地方才能让函数返回对应的柱状图字符串?

解决方案

核心修改思路是将原本直接打印的内容全部收集到一个字符串列表,最后拼接成完整字符串返回,替代直接输出的逻辑。具体修改如下:

  1. 初始化一个空列表chart_lines,用于存储柱状图的每一行内容
  2. 把所有print语句替换为向chart_lines添加字符串的操作,注意合并print的多参数为单个完整字符串
  3. 处理分类名称的循环时,先拼接出每一行的完整字符串,再添加到列表
  4. 函数最后返回用'\n'连接所有行的结果

修改后的完整代码:

def create_spend_chart(categories):
    withdrawals_name = []
    withdrawals_sum = 0
    for category in categories:
        withdrawals_sum += category.widthdrawal_tracker
        withdrawals_name.append([category.name, category.widthdrawal_tracker])

    for withdrawal in withdrawals_name:
        withdrawal.append(int((withdrawal[1]/withdrawals_sum) * 10) * 10)

    vals_to_be_evaluated = [a[2] for a in withdrawals_name]

    # 初始化存储每一行的列表
    chart_lines = []
    chart_lines.append('Percentage spent by category')

    for row in range(100, -10, -10):
        bar_chars = ['o' if digit >= row else ' ' for digit in vals_to_be_evaluated]
        bar_str = ' '.join(bar_chars)
        # 根据行号格式化前缀,合并为完整行字符串
        if row == 100:
            line = f"{row}| {bar_str}"
        elif row < 100 and row > 0:
            line = f" {row}| {bar_str}"
        else:  # row == 0
            line = f"  {row}| {bar_str}"
        chart_lines.append(line)
    
    # 添加分隔线
    separator = ' ' *4 + '-'*(2*len(vals_to_be_evaluated)+1)
    chart_lines.append(separator)

    str_val_eval = [a[0] for a in withdrawals_name]
    max_str_len = max(len(name) for name in str_val_eval)

    # 处理分类名称行
    for x in range(max_str_len):
        line_parts = [' ' *5]
        for name in str_val_eval:
            if x < len(name):
                line_parts.append(name[x])
            else:
                line_parts.append(' ')
            line_parts.append(' ')  # 每个字符后加空格
        # 拼接成完整行,保证格式与原输出一致
        line = ''.join(line_parts).rstrip() + ' '
        chart_lines.append(line)
    
    # 用换行符连接所有行,返回完整字符串
    return '\n'.join(chart_lines)

现在调用print(create_spend_chart([...]))时,函数会返回正确的柱状图字符串,print输出时就不会出现末尾的None了。

内容的提问来源于stack exchange,提问作者will_keep_on_learning

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 11:10:42