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

如何在Python函数中传入可变变量并实现赋值修改?

解决Python函数传参修改外部变量的问题

先看你代码里的两个核心问题:

  1. 逻辑判断错误:answers in user_input是检查集合是否是字符串的子串,这完全反了,应该判断用户输入是否在有效答案集合里。
  2. 无法修改外部变量:你直接传sword.type,本质是把这个属性的当前值传给函数,函数里对variable_name的赋值只是改了局部变量,根本影响不到外部的sword.type。

下面给你两种实用的解决方案:

方案一:返回有效值,外部赋值(最推荐)

这是Python里最清晰的写法,让函数专注获取有效输入,把结果返回给外部变量:

def get_valid_input(valid_answers, prompt=""):
    while True:
        user_input = input(prompt).strip().lower()  # 去空格+转小写,兼容大小写输入
        if user_input in valid_answers:
            return user_input
        print("incorrect input, please try again.")

# 调用时直接赋值给目标变量
sword.type = get_valid_input(
    {"katana", "claymore", "dagger"},
    "Choose your sword type (katana/claymore/dagger): "
)

方案二:传递对象+属性名,直接修改

如果不想在外部赋值,可以把对象和属性名传给函数,用setattr直接修改对象属性:

def set_valid_input(valid_answers, obj, attr_name, prompt=""):
    while True:
        user_input = input(prompt).strip().lower()
        if user_input in valid_answers:
            setattr(obj, attr_name, user_input)
            break
        print("incorrect input, please try again.")

# 调用方式,直接修改sword的type属性
set_valid_input(
    {"katana", "claymore", "dagger"},
    sword,
    "type",
    "Choose your sword type (katana/claymore/dagger): "
)

额外优化点

  • 函数名改用Python规范的小写下划线命名,比驼峰式更易读。
  • 增加输入提示,让用户明确知道该输入什么,提升游戏体验。
  • 处理大小写和空格,避免用户输入时的小失误导致判定错误。

内容的提问来源于stack exchange,提问作者Bow the bro

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 09:01:01