Sami Samp Sami Samp - 3 months ago 7
Python Question

Make python for loop go only once

Alright, so I'm trying to make a Facebook bot over here to do some stuff for me, But I don't really think that matters for you.

Anyway, in order to achieve what I want to do I need to do some stuff. So, using the Facebook API I am getting some posts id with the following code:

for posts in parsed_json:
post_id = posts.get('id')
post_url = "http://facebook.com/" + str(post_id)
text_save(post_url)


But the problem is that this code gets me the last 25 post ID's and I only need the last one.
So bassicaly what I'm trying to do is: Get the last post ID and then execute the text_save() function with that.

But that loop gets me 25 ids, and I don't need them. I need only the first one.

So how do I limit the for loop to run only once? I tried the following thing:

a = 0
while a < 1:
for posts in parsed_json:
post_id = posts.get('id')
post_url = "http://facebook.com/" + str(post_id)
text_save(post_url)
a = a + 1


But that didn't really work out, it still goes through it 25 times. Any ideeas?

Answer

To get the last value (or first), simply use "http://facebook.com/" + str(parsed_json[-1].get('id')) (or parsed_json[0])

If you want to use loop instead, to save just the last value, iterate and run the command afterwards:

post_url = ''
for posts in parsed_json:
    post_id = posts.get('id')
    post_url = "http://facebook.com/" + str(post_id)
text_save(post_url)

To break from a loop after one interation use:

a = 0
for posts in parsed_json:
    if a <= 1: break
    post_id = posts.get('id')
    post_url = "http://facebook.com/" + str(post_id)
    text_save(post_url)
    a += 1