首页 > 解决方案 > Substitute a local value in the global expression inside a function

问题描述

I want to substitute some parameters inside the function (i) without creating additional parameters of the function f(parameters), (ii) without changing variables globally. The problem is that one variable is defined outside the function and I would like to keep it this way (z can be potentially a result of many other preceding cells).

import sympy
x_hh=sympy.Symbol("x_hh") 
z=x_hh+2;

def v():
    x_hh=2;
    a=1;
    utility = a*z
    return utility
display(v())

As the output I have x_hh+2, but I want to have 4.

标签: pythonfunctionvariable-assignment

解决方案


您的代码将从上到下进行解释。所以z=x_hh+2;只会在开始时被调用一次。

您可以简单地在函数内创建一个新变量:

import sympy
x_hh=sympy.Symbol("x_hh") 
z=x_hh+2

def v():
    x_hh=2; #the value of x_hh was changed here
    new_var = x_hh+2 # this variable will be up-to-date and won't affect z
    a=1;
    utility = a*new_var #we use the new variable instead of z
    return utility
display(v())

推荐阅读