Python Forum

Full Version: SAS Equivalent of Macro variable in Python
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am writing code to simulate different scenarios. However, it gets cumbersome to type in the values for different scenarios. I was hoping I could use something similar to a SAS Macro variable so that I can change the values at the top and the bottom would invoke (via the macro variable) the changes

I've tried various options but no luck

/* Defining the Macro Variable */
%LET a = 10;
%LET b = 5;

/* Invoking it */
x = &a + &b
The answer is 15

thanks

PC
I must be missing something here. Why do variables not work for your project?

a = 10
b = 5

x = a + b
print(x)
You don't need macro variables in Python. Python is much more flexible than SAS.

a = 10
b = 5
x = a + b
print(x)   # prints 15
If you want to run the same code for different scenarios, you should put that code into a function or a class, and use parameters:

def add(a, b):
    return a + b
x = add(5, 10)
print(x)        # prints 15
thank you ichabod801. Very helpful.

PC
SAS macro is much more flexible that the construction mentioned above in Python.
SAS macro variable is taken any text. Like
%let a=this is a text;
contents of a is string between '=' and ';'
Then it is converted into code after processing part of multi-line code text, containing
referencing &a.
in Python so far I have found the way only to use variables defined in Python in expressions
used for data frames with referencing @var_name.
For example, very easy task to filter some data frame on columns of type object
which works in code like this

adsl[(adsl['sex']==b'1') & (adsl['area']==b'2') ]

If I need to specify the values for selection somewhere before this code, there is no way to do this.
While the following code is working well
age_min=25
age_max=64
year_min=1972
year_max=2002
adsl1.query( "(@age_min<=age<=@age_max)  & (@year_min<=year<=@year_max)")