1

Let me edit my question to clarify. Here is the python code:

decade_begin = 1970

while decade_begin <= 1994:
    for x in range(0, 10):
        a= decade_begin + x
    decade_begin = a+1
    decade_end=a

print "year_",decade_begin,"s" #start year 

The output of the last line is:

year_1980s
year_1990s

I want to be able to create a variable such that:

year_1990s = [a]

In stata this is quite easy, using a local macro `x'. But in python I think mixing string and int in a variable name is not allowed.

forval i = 1979/1994 {
whatever if year == `i' 
save year_`i'.dta, replace
}

Any ideas on how to implement in python?

noiivice
  • 400
  • 2
  • 15
  • For those familiar with Python, but not with STATA, could you explain what `x' does? Do you mean something like [format literals](http://stackoverflow.com/documentation/python/1019/string-formatting/4021/format-literals#t=201611212058243848285)? – tobias_k Nov 21 '16 at 20:59
  • I think it is called a local macro in STATA. The simplest explanation I found is here: https://www.ssc.wisc.edu/sscc/pubs/stata_prog1.htm – noiivice Nov 21 '16 at 21:08
  • It **is** called a local macro. That is quite explicit at source http://www.stata.com/help.cgi?foreach But I doubt that knowing Stata [NB] terminology helps answer the python question, which is a question of how to loop over a list. – Nick Cox Nov 21 '16 at 21:11
  • Still not sure whether this question is about [string formatting](http://stackoverflow.com/documentation/python/1019/string-formatting#t=201611212151031953559) or ["variable variables"](http://stackoverflow.com/q/1373164/1639625) (but probably not about loops or file access). – tobias_k Nov 21 '16 at 21:50

2 Answers2

1

Something like this is a rough equivalent:

for x in ["apple", "banana", "orange"]:
    with open(x + ".data", "w") as outfile:
        outfile.write("whatever")
kindall
  • 178,883
  • 35
  • 278
  • 309
0

If I understand correctly, you'd like to create a variable name using a string to name the variable. (The equivalent of local macros in Stata are called variables in Python). You can do this using the exec function:

>>> for i in range(1979, 1995):
...    exec("name_" + str(i) + " = " + str(i))

>>> print(name_1994)
1994

This code assumes you're using Python 3. If you're using Python 2, remove the outer parentheses for the lines with exec and print.

Using exec is not the best way to approach this problem in Python, however (as explained here). You will likely run into problems later on if you try to code in Python the same way you're used to coding in Stata.

A better approach might be to create a dictionary and use a different key for each number. For example:

>>> names = {}
>>> for i in range(1979, 1995):
...    names[i] = i
>>> print(names)
{1979: 1979, 1980: 1980, 1981: 1981, 1982: 1982, 1983: 1983, 1984: 1984, 1985: 1985, 1986: 1986, 1987: 1987, 1988: 1988, 1989: 1989, 1990: 1990, 1991: 1991, 1992: 1992, 1993: 1993, 1994: 1994}
nhmc
  • 1