You need to enable JavaScript to run this app. 如何实现可交互式多次为整数加2的Python自定义函数add_two
优惠活动
大模型
产品
解决方案
定价
更多

如何实现可交互式多次为整数加2的Python自定义函数add_two

单次调用add_two实现多次累加交互的方案

核心逻辑:在函数内部嵌入循环判断逻辑,一次调用即可完成多轮询问、累加的全流程,无需外部重复触发函数。

完整实现代码

def add_two(initial_n):
    # 用内部变量存储当前值,避免直接修改不可变类型形参
    current_n = initial_n
    while True:
        # 打印交互询问
        print("Would you like to add a two to n ?")
        # 获取用户输入,去除首尾空白字符避免判断错误
        user_input = input().strip()
        if user_input == "Yes":
            current_n += 2
            print(f"The new n is {current_n}")
        elif user_input == "No":
            # 收到No时终止循环,退出函数
            break
    # 可选:返回最终计算结果供外部使用
    return current_n

测试调用方式

n = 3
# 仅需一次调用即可完成全交互流程
final_n = add_two(n)

预期运行交互(完全匹配示例)

Would you like to add a two to n ?
Yes
The new n is 5
Would you like to add a two to n ?
Yes
The new n is 7
Would you like to add a two to n ?
No

补充说明

  • 若需要兼容更多输入格式(比如大小写不敏感、支持缩写y/n),可修改输入判断逻辑为:
    user_input = input().strip().lower()
    if user_input in ("yes", "y"):
        current_n += 2
        print(f"The new n is {current_n}")
    elif user_input in ("no", "n"):
        break
    
  • 因为Python中整数是不可变类型,直接修改传入的形参不会影响外部变量,因此函数内部用独立变量存储当前累加值,如需更新外部的n变量,可在调用后赋值:n = add_two(n)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.25 16:36:04