-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!

  • Maybe `print Books, x`? What is `books`? Why iterate over a list of one element? Also you should upgrade to Python 3, where `print` is a function. – jonrsharpe Jun 21 '19 at 14:11
  • 2
    You should be using a list, not variables named with sequential numbers. – Ry- Jun 21 '19 at 14:12
  • This is a really bad way of coding – AK47 Jun 21 '19 at 14:18
  • So, what I want to do just isn't good procedure in Python? – Obsidian Scarlet Jun 21 '19 at 14:18
  • 1
    Its not really good procedure in most programming languages, naming variables with a counter suggests you need a different data structure – Sayse Jun 21 '19 at 14:20
  • Even if just wanted a terse way to print a bunch of variables that have very similar names without typing them all out? I mean, I confess, I'd probably find ways to use it beyond that... – Obsidian Scarlet Jun 21 '19 at 14:25

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
AK47
  • 8,646
  • 6
  • 37
  • 61
Vaibhav Sharma
  • 891
  • 4
  • 14