1

I'm making the transition from java to python and I'm confused about how for loops work in python. I know basically all for loops in python are for-each loops, but that's not what I need. I've built a scraper, and I'm just trying to condense the code a little. My current issue is that I call for status codes in my responses, so I have ten or twelve lines of response1.status_code response2.status_code etc. If I were in java, I could write something along the lines of

for (int i=1; i<=12; i++){
    if (response[i].status_code != 200) 
        System.out.print("error in response"+[i])};

but that doesn't seem to exist in python, so I'm not quite sure where to turn. Any advice is appreciated!

  • 3
    for i in range(1, 12+1): –  Dec 27 '21 at 18:10
  • Use enumerate: https://docs.python.org/3/library/functions.html#enumerate – Mark Dec 27 '21 at 18:11
  • Could also be "for r in response" or "for r in response[1:12+1]". –  Dec 27 '21 at 18:12
  • You should work though one of the many good introductory materials for python. It is really nothing like Java and so building a good foundation of pythonic concepts will save you a lot of time in the long run. – erik258 Dec 27 '21 at 18:12
  • In Python you typically do `for x in obj`. What's also quite useful is `for i, x in enumerate(obj)` – niko Dec 27 '21 at 18:13
  • If `response1` and `response2` are two separate variables then this will not work (are you sure it works like that in Java?). You'd be better off making a list instead – Tomerikoo Dec 27 '21 at 18:15
  • Does this answer your question? [How do I create variable variables?](https://stackoverflow.com/q/1373164/6045800) – Tomerikoo Dec 27 '21 at 18:28

2 Answers2

4

You can use enumerate.

for index,content in enumerate(array):
    print(array[index])
    print(content) # both prints same stuff

Soyokaze
  • 157
  • 8
1

You can use this, if you already have the list / array but don't know the size yet.

for idx,data in enumerate(content_list):
    print(idx) # will print the index of the loop starting from 0
    print(data) # will print the actual data,
    print(content_list[idx]) # will manually access the list using the index. both this and data will print the same thing

If you want to do a for loop with a set range, do this,

for i in range(1,12+1): #need to do plus 1 because python is upper bound exclusive
    print(i)

or a while loop like this.

i = 1
while i <= 12: #loop will end when i becomes 12.
    print(i)
    i += 1 #increments by 1

If each item is a separate variable and not a list, try this,

for i in range(1,12+1): 
    if eval(f'response{i}.status_code != 200'): #this is an eval function with an f string, the curly braces will dynamically assign the variable on each loop
        print("error in response" + str(i)) #you cant concat a string and int together unless you convert the int to a string like this.

anarchy
  • 3,709
  • 2
  • 16
  • 48