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

Python函数中如何获取传入的参数n并打印对应提示信息

修复方案

你遇到的问题是函数内部的参数n在函数外部无法直接访问,直接打印n会触发未定义错误。这里给你两种简单可行的修复方式:

方式一:调用时保存传入的n值

在调用函数前,把要传入的n值存到变量里,后续打印时直接使用这个变量:

def RemoveChars(word, n):
    print("Original string: ", word, ".")
    x = word[n:]
    return x


print("Removing characters from a string")
# 保存n的值
n_val = 4
print(RemoveChars("pynative", n_val))
print(f"Removed the first {n_val} letters.")

n_val = 2
print(RemoveChars("pynative", n_val))
print(f"Removed the first {n_val} letters.")

方式二:修改函数返回多个值

让函数同时返回处理后的字符串和传入的n参数,调用时就能直接拿到n用于打印:

def RemoveChars(word, n):
    print("Original string: ", word, ".")
    x = word[n:]
    # 同时返回处理后的字符串和n
    return x, n


print("Removing characters from a string")
result, n_val = RemoveChars("pynative", 4)
print(result)
print(f"Removed the first {n_val} letters.")

result, n_val = RemoveChars("pynative", 2)
print(result)
print(f"Removed the first {n_val} letters.")

另外推荐使用Python的f-string格式化打印语句,相比字符串拼接更简洁易读。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 02:35:23