Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

For loop in Python with indices

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading