Home > Blockchain >  How do i keep validating string word length until it satisfies the condition?
How do i keep validating string word length until it satisfies the condition?

Time:04-16

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 "'")

CodePudding user response:

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:

  1. Your while loop needed a change from and to or (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)
  2. You need to recalculate the value of number each time you get a new value from the API

CodePudding user response:

Your while loop needs to contain the or statement and the last condition should be number>=20

while number<=3 or number>=20:
    

CodePudding user response:

Keep in mind though that you don't update number in the loop block, so the condition will never change, even with the corrected number<=3 or number>=20 condition.

CodePudding user response:

Finally This is the solution if someone needs the same thing

import requests
number = 0
while number<=3 or number>=30:
    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 "'")
    word_list = quote.split()
    number = len(word_list)
    print(number)
  • Related