I wrote a recursive function to detect whether or not the url of any given post contained " .jpg " or " .png ". But if it doesn't find an image on it's first try, it returns " None ". If I put a print statement in the function right below the "submission =" it does print out, but the string doesn't seem to exist when I try to return that value. My goal is to write a function that will always return an image url. Also I am writing this for a discord bot, so if I should be using async praw let me know.
Thanks.
import praw
import random
reddit = praw.Reddit(client_id = "CLIENT_ID", client_secret = "CLIENT_SECRET", user_agent= "USER_AGENT")
def is_image():
submission = random.choice([i for i in reddit.subreddit("RANDOM REDDIT").top("all", limit=100)])
if ".jpg" in submission.url or ".png" in submission.url:
return submission.url
is_image()
return
print(is_image())
Instead of pointlessly calling is_image()
after the if-statement, you should return it.
def is_image():
submission = random.choice([i for i in reddit.subreddit("RANDOM REDDIT").top("all", limit=100)])
if ".jpg" in submission.url or ".png" in submission.url:
return submission.url
return is_image()
print(is_image())
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.