So I have written this code to generate a random anime quote from the given website
could someone help me how can I make it so that the code checks if the quote has certain number of words and validates it accordingly
eg. If the quote has just 3 words I want it to try again
also if the quote has more than 20 words I want it to try again
I tried writing a while loop for it but it wasn’t working any answers would be appreciated
url = "https://animechan.vercel.app/api/random"
data = requests.get(url).json()
anime = data["anime"]
quote =data["quote"]
character =data["character"]
print("Anime : "+anime)
print(quote)
print(" '"+character+"'")
the while loop solution i came up with
quote = ""
word_list = quote.split()
number = len(word_list)
while number<=3 and number>=15:
url = "https://animechan.vercel.app/api/random"
data = requests.get(url).json()
anime = data["anime"]
quote =data["quote"]
character =data["character"]
print("Anime : "+anime)
print(quote)
print(" '"+character+"'")
>Solution :
I think this might be what you’re looking for (I’m assuming you wanted to stop on the first quote you found that was between 3 and 15 words long):
quote = ""
word_list = quote.split()
number = len(word_list)
while number<=3 or number>=15:
url = "https://animechan.vercel.app/api/random"
data = requests.get(url).json()
anime = data["anime"]
quote =data["quote"]
character =data["character"]
word_list = quote.split()
number = len(word_list)
print("Anime : "+anime)
print(quote)
print(" '"+character+"'")
I only made a couple of changes to your original:
- Your while loop needed a change from
andtoor(the length can never be both less than or equal to 3 and greater than or equal to 15, so the loop never got the chance to run) - You need to recalculate the value of
numbereach time you get a new value from the API