-1

I want to initialize and assign variables in a single loop, like I used to be able to in Stata, using a static element + an iterable element. I've edited the examples for clarity. The reason I want this is because it allows me to perform an operation on variables that have different contents in one loop. I can't just print a fixed string followed by something else.

Kind of like (pseudocode):

for each `x' in 1/10:
 print var`x' 

And this would print, not "var1, var2, var3, etc." but the actual values of contained within var1, var2, and var3, so long as they had been previously defined.

Or you could even do things like this, again more pseudocode:

foreach `x' in 1/10:
 thing`x' = `x'

This would both initialize the variable and put a value into it, in one step, in the same loop. Is there a way to do this sort of thing in python, or is it, as I've read elsewhere, "unpythonlike" and more or less forbidden?

I don't have a pressing problem at the moment. In the worst case, I can just link together long chains of print statements. But it bothers me that I can't just print the results I want by calling a bunch of serial variables in a loop. I've tried variations of

Books1 = Dogs
Books2 = Cats
Books3 = Lemurs

for x in range(10):
 for y in [books]:
  print y, x

But that just outputs something like

Books1
Books2 
Books3

...

When I want:


Dogs
Cats
Lemurs

Would appreciate if someone could point me the right direction!

1 Answers1

0

You dont need to iterate over books:

for idx in range(10):
    print("Author's name", idx)

>> Author's name 0
>> Author's name 1
>> Author's name 2
>> Author's name 3
>> Author's name 4
>> Author's name 5
>> Author's name 6
>> Author's name 7
>> Author's name 8
>> Author's name 9
Alan Kavanagh
  • 9,425
  • 7
  • 41
  • 65
static const
  • 953
  • 4
  • 16